Example usage for android.net.wifi WifiManager getConnectionInfo

List of usage examples for android.net.wifi WifiManager getConnectionInfo

Introduction

In this page you can find the example usage for android.net.wifi WifiManager getConnectionInfo.

Prototype

public WifiInfo getConnectionInfo() 

Source Link

Document

Return dynamic information about the current Wi-Fi connection, if any is active.

Usage

From source file:ua.mkh.settings.full.MainActivity.java

private void ButtonTextWifi() {
    TextView textwifi = (TextView) findViewById(R.id.textwifi);
    if (wifi.isWifiEnabled()) {
        textwifi.setText(R.string.on);/* w w w.  j  av a  2  s.co m*/
    } else {
        textwifi.setText(R.string.off);
    }

    WifiManager manager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
    if (manager.isWifiEnabled()) {
        WifiInfo wifiInfo = manager.getConnectionInfo();
        if (wifiInfo != null) {
            DetailedState state = WifiInfo.getDetailedStateOf(wifiInfo.getSupplicantState());
            if (state == DetailedState.CONNECTED || state == DetailedState.OBTAINING_IPADDR) {
                String wi = wifiInfo.getSSID().replace('"', ' ');
                textwifi.setText(wi);

            }
        }
    }

}

From source file:com.landenlabs.all_devtool.NetFragment.java

public void updateList() {
    // Time today = new Time(Time.getCurrentTimezone());
    // today.setToNow();
    // today.format(" %H:%M:%S")
    Date dt = new Date();
    m_titleTime.setText(m_timeFormat.format(dt));

    boolean expandAll = m_list.isEmpty();
    m_list.clear();//from   w  ww.  j a v  a  2 s  .c om

    // Swap colors
    int color = m_rowColor1;
    m_rowColor1 = m_rowColor2;
    m_rowColor2 = color;

    ActivityManager actMgr = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);

    try {
        String androidIDStr = Settings.Secure.getString(getContext().getContentResolver(),
                Settings.Secure.ANDROID_ID);
        addBuild("Android ID", androidIDStr);

        try {
            AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getContext());
            final String adIdStr = adInfo.getId();
            final boolean isLAT = adInfo.isLimitAdTrackingEnabled();
            addBuild("Ad ID", adIdStr);
        } catch (IOException e) {
            // Unrecoverable error connecting to Google Play services (e.g.,
            // the old version of the service doesn't support getting AdvertisingId).
        } catch (GooglePlayServicesNotAvailableException e) {
            // Google Play services is not available entirely.
        }

        /*
        try {
        InstanceID instanceID = InstanceID.getInstance(getContext());
        if (instanceID != null) {
            // Requires a Google Developer project ID.
            String authorizedEntity = "<need to make this on google developer site>";
            instanceID.getToken(authorizedEntity, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
            addBuild("Instance ID", instanceID.getId());
        }
        } catch (Exception ex) {
        }
        */

        ConfigurationInfo info = actMgr.getDeviceConfigurationInfo();
        addBuild("OpenGL", info.getGlEsVersion());
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    // --------------- Connection Services -------------
    try {
        ConnectivityManager connMgr = (ConnectivityManager) getActivity()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        final NetworkInfo netInfo = connMgr.getActiveNetworkInfo();
        if (netInfo != null) {
            Map<String, String> netListStr = new LinkedHashMap<String, String>();

            putIf(netListStr, "Available", "Yes", netInfo.isAvailable());
            putIf(netListStr, "Connected", "Yes", netInfo.isConnected());
            putIf(netListStr, "Connecting", "Yes", !netInfo.isConnected() && netInfo.isConnectedOrConnecting());
            putIf(netListStr, "Roaming", "Yes", netInfo.isRoaming());
            putIf(netListStr, "Extra", netInfo.getExtraInfo(), !TextUtils.isEmpty(netInfo.getExtraInfo()));
            putIf(netListStr, "WhyFailed", netInfo.getReason(), !TextUtils.isEmpty(netInfo.getReason()));
            if (Build.VERSION.SDK_INT >= 16) {
                putIf(netListStr, "Metered", "Avoid heavy use", connMgr.isActiveNetworkMetered());
            }

            netListStr.put("NetworkType", netInfo.getTypeName());
            if (connMgr.getAllNetworkInfo().length > 1) {
                netListStr.put("Available Networks:", " ");
                for (NetworkInfo netI : connMgr.getAllNetworkInfo()) {
                    if (netI.isAvailable()) {
                        netListStr.put(" " + netI.getTypeName(), netI.isAvailable() ? "Yes" : "No");
                    }
                }
            }

            if (netInfo.isConnected()) {
                try {
                    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                            .hasMoreElements();) {
                        NetworkInterface intf = en.nextElement();
                        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
                                .hasMoreElements();) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress()) {
                                if (inetAddress.getHostAddress() != null) {
                                    String ipType = (inetAddress instanceof Inet4Address) ? "IPv4" : "IPv6";
                                    netListStr.put(intf.getName() + " " + ipType, inetAddress.getHostAddress());
                                }
                                // if (!TextUtils.isEmpty(inetAddress.getHostName()))
                                //     listStr.put( "HostName", inetAddress.getHostName());
                            }
                        }
                    }
                } catch (Exception ex) {
                    m_log.e("Network %s", ex.getMessage());
                }
            }

            addBuild("Network...", netListStr);
        }
    } catch (Exception ex) {
        m_log.e("Network %s", ex.getMessage());
    }

    // --------------- Telephony Services -------------
    TelephonyManager telephonyManager = (TelephonyManager) getActivity()
            .getSystemService(Context.TELEPHONY_SERVICE);
    if (telephonyManager != null) {
        Map<String, String> cellListStr = new LinkedHashMap<String, String>();
        try {
            cellListStr.put("Version", telephonyManager.getDeviceSoftwareVersion());
            cellListStr.put("Number", telephonyManager.getLine1Number());
            cellListStr.put("Service", telephonyManager.getNetworkOperatorName());
            cellListStr.put("Roaming", telephonyManager.isNetworkRoaming() ? "Yes" : "No");
            cellListStr.put("Type", getNetworkTypeName(telephonyManager.getNetworkType()));

            if (Build.VERSION.SDK_INT >= 17) {
                if (telephonyManager.getAllCellInfo() != null) {
                    for (CellInfo cellInfo : telephonyManager.getAllCellInfo()) {
                        String cellName = cellInfo.getClass().getSimpleName();
                        int level = 0;
                        if (cellInfo instanceof CellInfoCdma) {
                            level = ((CellInfoCdma) cellInfo).getCellSignalStrength().getLevel();
                        } else if (cellInfo instanceof CellInfoGsm) {
                            level = ((CellInfoGsm) cellInfo).getCellSignalStrength().getLevel();
                        } else if (cellInfo instanceof CellInfoLte) {
                            level = ((CellInfoLte) cellInfo).getCellSignalStrength().getLevel();
                        } else if (cellInfo instanceof CellInfoWcdma) {
                            if (Build.VERSION.SDK_INT >= 18) {
                                level = ((CellInfoWcdma) cellInfo).getCellSignalStrength().getLevel();
                            }
                        }
                        cellListStr.put(cellName, "Level% " + String.valueOf(100 * level / 4));
                    }
                }
            }

            for (NeighboringCellInfo cellInfo : telephonyManager.getNeighboringCellInfo()) {
                int level = cellInfo.getRssi();
                cellListStr.put("Cell level%", String.valueOf(100 * level / 31));
            }

        } catch (Exception ex) {
            m_log.e("Cell %s", ex.getMessage());
        }

        if (!cellListStr.isEmpty()) {
            addBuild("Cell...", cellListStr);
        }
    }

    // --------------- Bluetooth Services (API18) -------------
    if (Build.VERSION.SDK_INT >= 18) {
        try {
            BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            if (bluetoothAdapter != null) {

                Map<String, String> btListStr = new LinkedHashMap<String, String>();

                btListStr.put("Enabled", bluetoothAdapter.isEnabled() ? "yes" : "no");
                btListStr.put("Name", bluetoothAdapter.getName());
                btListStr.put("ScanMode", String.valueOf(bluetoothAdapter.getScanMode()));
                btListStr.put("State", String.valueOf(bluetoothAdapter.getState()));
                Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
                // If there are paired devices
                if (pairedDevices.size() > 0) {
                    // Loop through paired devices
                    for (BluetoothDevice device : pairedDevices) {
                        // Add the name and address to an array adapter to show in a ListView
                        btListStr.put("Paired:" + device.getName(), device.getAddress());
                    }
                }

                BluetoothManager btMgr = (BluetoothManager) getActivity()
                        .getSystemService(Context.BLUETOOTH_SERVICE);
                if (btMgr != null) {
                    // btMgr.getAdapter().
                }
                addBuild("Bluetooth", btListStr);
            }

        } catch (Exception ex) {

        }
    }

    // --------------- Wifi Services -------------
    final WifiManager wifiMgr = (WifiManager) getContext().getApplicationContext()
            .getSystemService(Context.WIFI_SERVICE);

    if (wifiMgr != null && wifiMgr.isWifiEnabled() && wifiMgr.getDhcpInfo() != null) {

        if (mSystemBroadcastReceiver == null) {
            mSystemBroadcastReceiver = new SystemBroadcastReceiver(wifiMgr);
            getActivity().registerReceiver(mSystemBroadcastReceiver, INTENT_FILTER_SCAN_AVAILABLE);
        }

        if (ActivityCompat.checkSelfPermission(getContext(),
                Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(getContext(),
                        Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            if (wifiMgr.getScanResults() == null || wifiMgr.getScanResults().size() != mLastScanSize) {
                mLastScanSize = wifiMgr.getScanResults().size();
                wifiMgr.startScan();
            }
        }

        Map<String, String> wifiListStr = new LinkedHashMap<String, String>();
        try {
            DhcpInfo dhcpInfo = wifiMgr.getDhcpInfo();

            wifiListStr.put("DNS1", Formatter.formatIpAddress(dhcpInfo.dns1));
            wifiListStr.put("DNS2", Formatter.formatIpAddress(dhcpInfo.dns2));
            wifiListStr.put("Default Gateway", Formatter.formatIpAddress(dhcpInfo.gateway));
            wifiListStr.put("IP Address", Formatter.formatIpAddress(dhcpInfo.ipAddress));
            wifiListStr.put("Subnet Mask", Formatter.formatIpAddress(dhcpInfo.netmask));
            wifiListStr.put("Server IP", Formatter.formatIpAddress(dhcpInfo.serverAddress));
            wifiListStr.put("Lease Time(sec)", String.valueOf(dhcpInfo.leaseDuration));

            WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
            if (wifiInfo != null) {
                wifiListStr.put("LinkSpeed Mbps", String.valueOf(wifiInfo.getLinkSpeed()));
                int numberOfLevels = 10;
                int level = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), numberOfLevels + 1);
                wifiListStr.put("Signal%", String.valueOf(100 * level / numberOfLevels));
                if (Build.VERSION.SDK_INT >= 23) {
                    wifiListStr.put("MAC", getMacAddr());
                } else {
                    wifiListStr.put("MAC", wifiInfo.getMacAddress());
                }
            }

        } catch (Exception ex) {
            m_log.e("Wifi %s", ex.getMessage());
        }

        if (!wifiListStr.isEmpty()) {
            addBuild("WiFi...", wifiListStr);
        }

        try {
            if (ActivityCompat.checkSelfPermission(getContext(),
                    Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.checkSelfPermission(getContext(),
                            Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                List<ScanResult> listWifi = wifiMgr.getScanResults();
                if (listWifi != null && !listWifi.isEmpty()) {
                    int idx = 0;

                    for (ScanResult scanResult : listWifi) {
                        Map<String, String> wifiScanListStr = new LinkedHashMap<String, String>();
                        wifiScanListStr.put("SSID", scanResult.SSID);
                        if (Build.VERSION.SDK_INT >= 23) {
                            wifiScanListStr.put("  Name", scanResult.operatorFriendlyName.toString());
                            wifiScanListStr.put("  Venue", scanResult.venueName.toString());
                        }

                        //        wifiScanListStr.put("  BSSID ",scanResult.BSSID);
                        wifiScanListStr.put("  Capabilities", scanResult.capabilities);
                        //       wifiScanListStr.put("  Center Freq", String.valueOf(scanResult.centerFreq0));
                        //       wifiScanListStr.put("  Freq width", String.valueOf(scanResult.channelWidth));
                        wifiScanListStr.put("  Level, Freq",
                                String.format("%d, %d", scanResult.level, scanResult.frequency));
                        if (Build.VERSION.SDK_INT >= 17) {
                            Date wifiTime = new Date(scanResult.timestamp);
                            wifiScanListStr.put("  Time", wifiTime.toLocaleString());
                        }
                        addBuild(String.format("WiFiScan #%d", ++idx), wifiScanListStr);
                    }
                }
            }
        } catch (Exception ex) {
            m_log.e("WifiList %s", ex.getMessage());
        }

        try {
            List<WifiConfiguration> listWifiCfg = wifiMgr.getConfiguredNetworks();

            for (WifiConfiguration wifiCfg : listWifiCfg) {
                Map<String, String> wifiCfgListStr = new LinkedHashMap<String, String>();
                if (Build.VERSION.SDK_INT >= 23) {
                    wifiCfgListStr.put("Name", wifiCfg.providerFriendlyName);
                }
                wifiCfgListStr.put("SSID", wifiCfg.SSID);
                String netStatus = "";
                switch (wifiCfg.status) {
                case WifiConfiguration.Status.CURRENT:
                    netStatus = "Connected";
                    break;
                case WifiConfiguration.Status.DISABLED:
                    netStatus = "Disabled";
                    break;
                case WifiConfiguration.Status.ENABLED:
                    netStatus = "Enabled";
                    break;
                }
                wifiCfgListStr.put(" Status", netStatus);
                wifiCfgListStr.put(" Priority", String.valueOf(wifiCfg.priority));
                if (null != wifiCfg.wepKeys) {
                    //               wifiCfgListStr.put(" wepKeys", TextUtils.join(",", wifiCfg.wepKeys));
                }
                String protocols = "";
                if (wifiCfg.allowedProtocols.get(WifiConfiguration.Protocol.RSN))
                    protocols = "RSN ";
                if (wifiCfg.allowedProtocols.get(WifiConfiguration.Protocol.WPA))
                    protocols = protocols + "WPA ";
                wifiCfgListStr.put(" Protocols", protocols);

                String keyProt = "";
                if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.NONE))
                    keyProt = "none";
                if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_EAP))
                    keyProt = "WPA+EAP ";
                if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK))
                    keyProt = "WPA+PSK ";
                wifiCfgListStr.put(" Keys", keyProt);

                if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.NONE)) {
                    // Remove network connections with no Password.
                    // wifiMgr.removeNetwork(wifiCfg.networkId);
                }

                addBuild("WiFiCfg #" + wifiCfg.networkId, wifiCfgListStr);
            }

        } catch (Exception ex) {
            m_log.e("Wifi Cfg List %s", ex.getMessage());
        }
    }

    if (expandAll) {
        // updateList();
        int count = m_list.size();
        for (int position = 0; position < count; position++)
            m_listView.expandGroup(position);
    }

    m_adapter.notifyDataSetChanged();
}

From source file:com.lgallardo.qbittorrentclient.RefreshListener.java

protected void getSettings() {
    // Preferences stuff
    sharedPrefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);

    builderPrefs = new StringBuilder();

    builderPrefs.append("\n" + sharedPrefs.getString("language", "NULL"));

    // Get values from preferences
    currentServer = sharedPrefs.getString("currentServer", "1");
    hostname = sharedPrefs.getString("hostname", "");
    subfolder = sharedPrefs.getString("subfolder", "");

    protocol = sharedPrefs.getString("protocol", "NULL");

    // If user leave the field empty, set 8080 port
    try {/*from   ww  w  .  j  ava  2s . c  o m*/
        port = Integer.parseInt(sharedPrefs.getString("port", "8080"));
    } catch (NumberFormatException e) {
        port = 8080;

    }
    username = sharedPrefs.getString("username", "NULL");
    password = sharedPrefs.getString("password", "NULL");
    https = sharedPrefs.getBoolean("https", false);

    // Check https
    if (https) {
        protocol = "https";
    } else {
        protocol = "http";
    }

    // Get refresh info
    auto_refresh = sharedPrefs.getBoolean("auto_refresh", true);

    try {
        refresh_period = Integer.parseInt(sharedPrefs.getString("refresh_period", "120000"));
    } catch (NumberFormatException e) {
        refresh_period = 120000;
    }

    // Get connection and data timeouts
    try {
        connection_timeout = Integer.parseInt(sharedPrefs.getString("connection_timeout", "10"));

        // New default value to make it work with qBittorrent 3.2.x
        if (connection_timeout < 10) {
            connection_timeout = 10;
        }
    } catch (NumberFormatException e) {
        connection_timeout = 10;
    }

    try {
        data_timeout = Integer.parseInt(sharedPrefs.getString("data_timeout", "20"));

        // New default value to make it work with qBittorrent 3.2.x
        if (data_timeout < 20) {
            data_timeout = 20;
        }

    } catch (NumberFormatException e) {
        data_timeout = 20;
    }

    sortby_value = sharedPrefs.getInt("sortby_value", 1);
    reverse_order = sharedPrefs.getBoolean("reverse_order", false);

    dark_ui = sharedPrefs.getBoolean("dark_ui", false);

    qb_version = sharedPrefs.getString("qb_version", "3.2.x");

    MainActivity.cookie = sharedPrefs.getString("qbCookie", null);

    // Get last state
    lastState = sharedPrefs.getString("lastState", "all");

    // Get last label
    //        lastLabel = sharedPrefs.getString("lastLabel", "all");
    lastLabel = sharedPrefs.getString("lastLabel", "all");
    currentLabel = lastLabel;

    // Notification check
    enable_notifications = sharedPrefs.getBoolean("enable_notifications", false);

    try {
        notification_period = Long.parseLong(sharedPrefs.getString("notification_period", "120000L"));
    } catch (NumberFormatException e) {
        notification_period = 120000L;
    }

    header = sharedPrefs.getBoolean("header", true);

    // Get package info
    PackageInfo pInfo = null;
    try {
        pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }

    // Get package name
    packageName = pInfo.packageName;
    packageVersion = pInfo.versionName;

    // Get AlternativeSpeedLimitsEnabled value
    alternative_speeds = sharedPrefs.getBoolean("alternativeSpeedLimitsEnabled", false);

    // Get local SSID properties
    ssid = sharedPrefs.getString("ssid", "");
    local_hostname = sharedPrefs.getString("local_hostname", null);

    // If user leave the field empty, set 8080 port
    try {
        local_port = Integer.parseInt(sharedPrefs.getString("local_port", "-1"));
    } catch (NumberFormatException e) {
        local_port = -1;

    }

    // Set SSI and local hostname and port
    if (ssid != null && !ssid.equals("")) {

        // Get SSID if WiFi
        WifiManager wifiMgr = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
        String wifiSSID = wifiInfo.getSSID();

        //            Log.d("Debug", "WiFi SSID: " + wifiSSID);
        //            Log.d("Debug", "SSID: " + ssid);

        if (wifiSSID.toUpperCase().equals("\"" + ssid.toUpperCase() + "\"")
                && wifiMgr.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {

            if (local_hostname != null && !local_hostname.equals("")) {
                hostname = local_hostname;
            }

            if (local_port != -1) {
                port = local_port;
            }

            //                Log.d("Debug", "hostname: " + hostname);
            //                Log.d("Debug", "port: " + port);
            //                Log.d("Debug", "local_hostname: " + local_hostname);
            //                Log.d("Debug", "local_port: " + local_port);

        }
    }

    // Get keystore for self-signed certificate
    keystore_path = sharedPrefs.getString("keystore_path" + currentServer, "");
    keystore_password = sharedPrefs.getString("keystore_password" + currentServer, "");

}

From source file:com.mozilla.SUTAgentAndroid.SUTAgentAndroid.java

public boolean setUpNetwork(String sIniFile) {
    boolean bRet = false;
    int lcv = 0;//from   w ww .  j a  v  a  2 s. c o  m
    int lcv2 = 0;
    WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    WifiConfiguration wc = new WifiConfiguration();
    DoCommand tmpdc = new DoCommand(getApplication());

    String ssid = tmpdc.GetIniData("Network Settings", "SSID", sIniFile);
    String auth = tmpdc.GetIniData("Network Settings", "AUTH", sIniFile);
    String encr = tmpdc.GetIniData("Network Settings", "ENCR", sIniFile);
    String key = tmpdc.GetIniData("Network Settings", "KEY", sIniFile);
    String eap = tmpdc.GetIniData("Network Settings", "EAP", sIniFile);
    String adhoc = tmpdc.GetIniData("Network Settings", "ADHOC", sIniFile);

    Toast.makeText(getApplication().getApplicationContext(), "Starting and configuring network",
            Toast.LENGTH_LONG).show();
    /*
            ContentResolver cr = getContentResolver();
            int nRet;
            try {
    nRet = Settings.System.getInt(cr, Settings.System.WIFI_USE_STATIC_IP);
    String foo2 = "" + nRet;
            } catch (SettingNotFoundException e1) {
    e1.printStackTrace();
            }
    */
    /*
            wc.SSID = "\"Mozilla-Build\"";
            wc.preSharedKey  = "\"MozillaBuildQA500\"";
            wc.hiddenSSID = true;
            wc.status = WifiConfiguration.Status.ENABLED;
            wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
    */
    wc.SSID = "\"" + ssid + "\"";
    //        wc.SSID = "\"Mozilla-G\"";
    //        wc.SSID = "\"Mozilla\"";

    if (auth.contentEquals("wpa2")) {
        wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
        wc.preSharedKey = null;
    }

    if (encr.contentEquals("aes")) {
        wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
        wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    }

    if (eap.contentEquals("peap")) {
        wc.eap.setValue("PEAP");
        wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
        wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X);
    }

    wc.status = WifiConfiguration.Status.ENABLED;

    if (!wifi.isWifiEnabled())
        wifi.setWifiEnabled(true);

    while (wifi.getWifiState() != WifiManager.WIFI_STATE_ENABLED) {
        Thread.yield();
        if (++lcv > 10000)
            return (bRet);
    }

    wl = wifi.createWifiLock(WifiManager.WIFI_MODE_FULL, "SUTAgent");
    if (wl != null)
        wl.acquire();

    WifiConfiguration foo = null;
    int nNetworkID = -1;

    List<WifiConfiguration> connsLst = wifi.getConfiguredNetworks();
    int nConns = connsLst.size();
    for (int i = 0; i < nConns; i++) {

        foo = connsLst.get(i);
        if (foo.SSID.equalsIgnoreCase(wc.SSID)) {
            nNetworkID = foo.networkId;
            wc.networkId = foo.networkId;
            break;
        }
    }

    int res;

    if (nNetworkID != -1) {
        res = wifi.updateNetwork(wc);
    } else {
        res = wifi.addNetwork(wc);
    }

    Log.d("WifiPreference", "add Network returned " + res);

    boolean b = wifi.enableNetwork(res, true);
    Log.d("WifiPreference", "enableNetwork returned " + b);

    wifi.saveConfiguration();

    WifiInfo wi = wifi.getConnectionInfo();
    SupplicantState ss = wi.getSupplicantState();

    lcv = 0;
    lcv2 = 0;

    while (ss.compareTo(SupplicantState.COMPLETED) != 0) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (wi != null)
            wi = null;
        if (ss != null)
            ss = null;
        wi = wifi.getConnectionInfo();
        ss = wi.getSupplicantState();
        if (++lcv > 60) {
            if (++lcv2 > 5) {
                Toast.makeText(getApplication().getApplicationContext(),
                        "Unable to start and configure network", Toast.LENGTH_LONG).show();
                return (bRet);
            } else {
                Toast.makeText(getApplication().getApplicationContext(), "Resetting wifi interface",
                        Toast.LENGTH_LONG).show();
                if (wl != null)
                    wl.release();
                wifi.setWifiEnabled(false);
                while (wifi.getWifiState() != WifiManager.WIFI_STATE_DISABLED) {
                    Thread.yield();
                }

                wifi.setWifiEnabled(true);
                while (wifi.getWifiState() != WifiManager.WIFI_STATE_ENABLED) {
                    Thread.yield();
                }
                b = wifi.enableNetwork(res, true);
                Log.d("WifiPreference", "enableNetwork returned " + b);
                if (wl != null)
                    wl.acquire();
                lcv = 0;
            }
        }
    }

    lcv = 0;
    while (getLocalIpAddress() == null) {
        if (++lcv > 10000)
            return (bRet);
    }

    Toast.makeText(getApplication().getApplicationContext(), "Network started and configured",
            Toast.LENGTH_LONG).show();
    bRet = true;

    return (bRet);
}

From source file:com.guardtrax.ui.screens.HomeScreen.java

private void loadPreferenceDataBase() {
    //get the default values
    //List<String> defaults = OptionsScreen.loadDefaults();

    String uniqueID = "";

    //get the IMEI number
    try {// ww  w.ja  v  a 2 s .c om
        TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        if (tm != null)
            uniqueID = tm.getDeviceId();
        if (uniqueID == null || uniqueID.length() == 0) {
            WifiManager wifimanager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            if (wifimanager != null)
                uniqueID = wifimanager.getConnectionInfo().getMacAddress();
        }
        if (uniqueID == null)
            uniqueID = BluetoothAdapter.getDefaultAdapter().getAddress();
        if (uniqueID == null)
            uniqueID = "123456789";
    } catch (Exception e) {
        uniqueID = "987654321";
    }

    String uniqueIdDB = Utility.getUniqueNumber(uniqueID);

    //get the type of phone  (GSM,CDMA) and put into constants
    GTConstants.PHONE_TYPE = getPhoneType();

    //Load into new database 
    preferenceDB.open();

    id = preferenceDB.insertRecord(GTConstants.LOCATIONUPDATESINTERVAL,
            GTConstants.LOCATIONUPDATEDISTANCEINTERVAL, GTConstants.SERVERIP,
            String.valueOf(GTConstants.SERVERPORT), GTConstants.PANIC_NUMBER, uniqueIdDB,
            String.valueOf(GTConstants.ACCELEROMETER_SPEED), GTConstants.LICENSE_ID, GTConstants.PHONE_TYPE,
            GTConstants.REGISTRATION);

    preferenceDB.close();

    //load into constants
    preferenceDB.open();
    cursor = preferenceDB.getRecordByRowID("1");

    saveInConstants(cursor);

    cursor.close();
    preferenceDB.close();

}