Example usage for android.net.wifi WifiConfiguration WifiConfiguration

List of usage examples for android.net.wifi WifiConfiguration WifiConfiguration

Introduction

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

Prototype

public WifiConfiguration() 

Source Link

Usage

From source file:ch.bfh.instacircle.CreateNetworkActivity.java

public void onClick(View view) {
    if (view == btnCreateNetwork) {
        // setting up the the configuration
        if (wifiapman.isWifiAPEnabled(wifiman)) {
            wifiapman.disableHotspot(wifiman, this);
        }/*from   w w  w  .j a v  a 2  s .  com*/

        WifiConfiguration wificonfig = new WifiConfiguration();
        wificonfig.SSID = txtNetworkName.getText().toString();
        wificonfig.preSharedKey = txtNetworkPIN.getText().toString();
        wificonfig.hiddenSSID = false;
        wificonfig.status = WifiConfiguration.Status.ENABLED;

        wificonfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
        wificonfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
        wificonfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
        wificonfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
        wificonfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
        wificonfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);

        // enabling the configuration
        wifiapman.enableHotspot(wifiman, wificonfig, this);
    }
}

From source file:nl.nikhef.eduroam.WiFiEduroam.java

private void saveWifiConfig() {
    WifiManager wifiManager = (WifiManager) this.getSystemService(WIFI_SERVICE);
    wifiManager.setWifiEnabled(true);//w ww  .j  av  a 2 s . c om

    WifiConfiguration currentConfig = new WifiConfiguration();

    List<WifiConfiguration> configs = null;
    for (int i = 0; i < 10 && configs == null; i++) {
        configs = wifiManager.getConfiguredNetworks();
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            continue;
        }
    }

    // Use the existing eduroam profile if it exists.
    boolean ssidExists = false;
    if (configs != null) {
        for (WifiConfiguration config : configs) {
            if (config.SSID.equals(surroundWithQuotes(ssid))) {
                currentConfig = config;
                ssidExists = true;
                break;
            }
        }
    }

    currentConfig.SSID = surroundWithQuotes(ssid);
    currentConfig.hiddenSSID = false;
    currentConfig.priority = 40;
    currentConfig.status = WifiConfiguration.Status.DISABLED;

    currentConfig.allowedKeyManagement.clear();
    currentConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);

    // GroupCiphers (Allow most ciphers)
    currentConfig.allowedGroupCiphers.clear();
    currentConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    currentConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    currentConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);

    // PairwiseCiphers (CCMP = WPA2 only)
    currentConfig.allowedPairwiseCiphers.clear();
    currentConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);

    // Authentication Algorithms (OPEN)
    currentConfig.allowedAuthAlgorithms.clear();
    currentConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);

    // Protocols (RSN/WPA2 only)
    currentConfig.allowedProtocols.clear();
    currentConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);

    // Enterprise Settings
    HashMap<String, String> configMap = new HashMap<String, String>();
    configMap.put(INT_SUBJECT_MATCH, subject_match);
    configMap.put(INT_ANONYMOUS_IDENTITY, "anonymous" + realm);
    configMap.put(INT_EAP, "TLS");
    configMap.put(INT_ENGINE, "1");
    configMap.put(INT_ENGINE_ID, "keystore");
    configMap.put(INT_CA_CERT, INT_CA_PREFIX + ca_name);
    configMap.put(INT_PRIVATE_KEY, INT_PRIVATE_KEY_PREFIX + client_cert_name);
    configMap.put(INT_PRIVATE_KEY_ID, INT_PRIVATE_KEY_ID_PREFIX + client_cert_name);
    configMap.put(INT_CLIENT_CERT, INT_CLIENT_CERT_PREFIX + client_cert_name);

    if (android.os.Build.VERSION.SDK_INT >= 11 && android.os.Build.VERSION.SDK_INT <= 17) {
        applyAndroid4_42EnterpriseSettings(currentConfig, configMap);
    } else if (android.os.Build.VERSION.SDK_INT >= 18) {
        applyAndroid43EnterpriseSettings(currentConfig, configMap);
    } else {
        throw new RuntimeException("API version mismatch!");
    }

    if (!ssidExists) {
        int networkId = wifiManager.addNetwork(currentConfig);
        wifiManager.enableNetwork(networkId, false);
    } else {
        wifiManager.updateNetwork(currentConfig);
        wifiManager.enableNetwork(currentConfig.networkId, false);
    }
    wifiManager.saveConfiguration();

}

From source file:org.csploit.android.WifiScannerActivity.java

private int performConnection(final ScanResult ap, final String key) {
    mWifiManager.disconnect();//from  w  w  w.ja  va  2 s.co m

    mCurrentKey = key;
    mCurrentAp = ap;

    WifiScannerActivity.this.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            if (key != null)
                mStatusText.setText(Html.fromHtml(getString(R.string.wifi_attempting_to) + " <b>" + ap.SSID
                        + "</b> " + getString(R.string.wifi_with_key) + " <b>" + key + "</b> ..."));
            else
                mStatusText.setText(
                        Html.fromHtml(getString(R.string.wifi_connecting_to) + " <b>" + ap.SSID + "</b> ..."));
        }
    });

    WifiConfiguration config = new WifiConfiguration();
    int network = -1;

    config.SSID = "\"" + ap.SSID + "\"";
    config.BSSID = ap.BSSID;

    /*
       * Configure security.
     */
    if (ap.capabilities.contains("WEP")) {
        config.wepKeys[0] = "\"" + key + "\"";
        config.wepTxKeyIndex = 0;
        config.status = WifiConfiguration.Status.ENABLED;
        config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
    } else if (ap.capabilities.contains("WPA"))
        config.preSharedKey = "\"" + key + "\"";

    else
        config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);

    network = mWifiManager.addNetwork(config);
    if (network != -1) {
        if (mWifiManager.saveConfiguration()) {
            config = NetworkManager.getWifiConfiguration(mWifiManager, config);

            // Make it the highest priority.
            network = config.networkId;

            int old_priority = config.priority, max_priority = NetworkManager.getMaxPriority(mWifiManager) + 1;

            if (max_priority > 9999) {
                NetworkManager.shiftPriorityAndSave(mWifiManager);
                config = NetworkManager.getWifiConfiguration(mWifiManager, config);
            }

            // Set highest priority to this configured network
            config.priority = max_priority;
            network = mWifiManager.updateNetwork(config);

            if (network != -1) {
                // Do not disable others
                if (mWifiManager.enableNetwork(network, false)) {
                    if (mWifiManager.saveConfiguration()) {
                        // We have to retrieve the WifiConfiguration after save.
                        config = NetworkManager.getWifiConfiguration(mWifiManager, config);
                        if (config != null) {
                            // Disable others, but do not save.
                            // Just to force the WifiManager to connect to it.
                            if (mWifiManager.enableNetwork(config.networkId, true)) {
                                return mWifiManager.reassociate() ? config.networkId : -1;
                            }
                        }
                    } else
                        config.priority = old_priority;
                } else
                    config.priority = old_priority;
            }
        }
    }

    return network;
}

From source file:tf.nox.wifisetup.WifiSetup.java

private void saveWifiConfig() {
    WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(WIFI_SERVICE);
    wifiManager.setWifiEnabled(true);/*  w  w w.  j  a v  a 2s.co m*/

    WifiConfiguration currentConfig = new WifiConfiguration();

    List<WifiConfiguration> configs = null;
    for (int i = 0; i < 10 && configs == null; i++) {
        configs = wifiManager.getConfiguredNetworks();
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            continue;
        }
    }

    if (check5g.isChecked()) {
        ssid = "34C3";
    } else {
        ssid = "34C3-legacy";
    }
    subject_match = "/CN=radius.c3noc.net";
    altsubject_match = "DNS:radius.c3noc.net";

    s_username = username.getText().toString();
    s_password = password.getText().toString();
    realm = "";
    if (s_username.equals("") && s_password.equals("")) {
        s_username = "34c3";
        s_password = "34c3";
    } else {
        if (s_username.indexOf("@") >= 0) {
            int idx = s_username.indexOf("@");
            realm = s_username.substring(idx);
        }
    }

    // Use the existing eduroam profile if it exists.
    boolean ssidExists = false;
    if (configs != null) {
        for (WifiConfiguration config : configs) {
            if (config.SSID.equals(surroundWithQuotes(ssid))) {
                currentConfig = config;
                ssidExists = true;
                break;
            }
        }
    }

    currentConfig.SSID = surroundWithQuotes(ssid);
    currentConfig.hiddenSSID = false;
    currentConfig.priority = 40;
    currentConfig.status = WifiConfiguration.Status.DISABLED;

    currentConfig.allowedKeyManagement.clear();
    currentConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);

    // GroupCiphers (Allow most ciphers)
    currentConfig.allowedGroupCiphers.clear();
    currentConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    currentConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    currentConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);

    // PairwiseCiphers (CCMP = WPA2 only)
    currentConfig.allowedPairwiseCiphers.clear();
    currentConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);

    // Authentication Algorithms (OPEN)
    currentConfig.allowedAuthAlgorithms.clear();
    currentConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);

    // Protocols (RSN/WPA2 only)
    currentConfig.allowedProtocols.clear();
    currentConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);

    // Enterprise Settings
    HashMap<String, String> configMap = new HashMap<String, String>();
    configMap.put(INT_SUBJECT_MATCH, subject_match);
    configMap.put(INT_ALTSUBJECT_MATCH, altsubject_match);
    configMap.put(INT_ANONYMOUS_IDENTITY, "anonymous" + realm);
    configMap.put(INT_IDENTITY, s_username);
    configMap.put(INT_PASSWORD, s_password);
    configMap.put(INT_EAP, "TTLS");
    configMap.put(INT_PHASE2, "auth=PAP");
    configMap.put(INT_ENGINE, "0");
    // configMap.put(INT_CA_CERT, INT_CA_PREFIX + ca_name);

    applyAndroid43EnterpriseSettings(currentConfig, configMap);

    if (!ssidExists) {
        int networkId = wifiManager.addNetwork(currentConfig);
        wifiManager.enableNetwork(networkId, false);
    } else {
        wifiManager.updateNetwork(currentConfig);
        wifiManager.enableNetwork(currentConfig.networkId, false);
    }
    wifiManager.saveConfiguration();

}

From source file:org.sltpaya.tool.Utils.java

/**
 * ?/*from w  ww .  j  a  v  a 2s  .c om*/
 *
 * @param ssid   ??
 * @param passwd ?
 *               ??? <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
 */
@SuppressWarnings("unused")
public static void startWifiAp(String ssid, String passwd) {
    if (mWifiManager == null)
        mWifiManager = (WifiManager) getContext().getSystemService(Context.WIFI_SERVICE);
    //wifi???wifi
    if (mWifiManager.isWifiEnabled())
        mWifiManager.setWifiEnabled(false);
    if (!isWifiApEnabled()) {
        Method method;
        try {
            //??0
            method = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class,
                    boolean.class);
            WifiConfiguration netConfig = new WifiConfiguration();

            netConfig.SSID = ssid;
            netConfig.preSharedKey = passwd;

            netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
            netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            method.invoke(mWifiManager, netConfig, true);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

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

public boolean setUpNetwork(String sIniFile) {
    boolean bRet = false;
    int lcv = 0;/*w  w  w  .  java2 s  . c om*/
    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:ac.robinson.bettertogether.hotspot.HotspotManagerService.java

private void finishConnectingWifiHotspot(@NonNull ConnectionOptions connectionOptions) {
    // set up new network - *must* be surrounded by " (see: https://stackoverflow.com/questions/2140133/)
    Log.d(TAG, "Connecting to Wifi network " + connectionOptions.mName);
    WifiConfiguration wifiConfiguration = new WifiConfiguration();
    WifiUtils.setConfigurationAttributes(wifiConfiguration, "\"" + connectionOptions.mName + "\"",
            "\"" + connectionOptions.mPassword + "\"");

    int savedNetworkId = WifiUtils.getWifiNetworkId(mWifiManager, wifiConfiguration.SSID);
    if (savedNetworkId >= 0) {
        Log.d(TAG, "Found saved Wifi network id");
        mHotspotId = savedNetworkId;/* w  w  w .j  a  v  a2  s .co m*/
    } else {
        Log.d(TAG, "Adding Wifi network");
        mHotspotId = mWifiManager.addNetwork(wifiConfiguration);
        // mWifiManager.saveConfiguration(); // can change network IDs(!) - not really needed, so disabled
        if (mHotspotId < 0) {
            Log.d(TAG, "Couldn't add Wifi network");
            mWifiConnectionErrorCount += 1;
            retryWifiConnection();
            return;
        }
    }

    // if we're auto-connected to a previous network (unlikely!), continue straight away; if not, reconnect
    WifiInfo currentConnection = mWifiManager.getConnectionInfo();
    if (currentConnection != null && wifiConfiguration.SSID.equals(currentConnection.getSSID())) {
        Log.d(TAG, "Continuing with current Wifi connection");
        connectWifiClient(connectionOptions.mIPAddress, connectionOptions.mPort);
    } else {
        Log.d(TAG, "Enabling Wifi network");
        mWifiManager.disconnect();
        if (!mWifiManager.enableNetwork(mHotspotId, true)) { // connect to our network - handle connection in receiver
            Log.d(TAG, "Couldn't enable Wifi network");
            mWifiConnectionErrorCount += 1;
            retryWifiConnection();
        } else {
            Log.d(TAG, "Wifi network enabled");
            mWifiManager.reconnect();
            setWifiErrorTimeout();
        }
    }
}

From source file:de.ub0r.android.wifibarcode.WifiBarcodeActivity.java

/**
 * Load wifi configurations./*w  w  w .  j a  va  2  s.  c o  m*/
 */
private void loadWifiConfigurations() {
    WifiAdapter adapter = (WifiAdapter) mSpConfigs.getAdapter();
    WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
    List<WifiConfiguration> wcs = wm.getConfiguredNetworks();
    String currentSSID = wm.getConnectionInfo().getSSID();
    Log.d(TAG, "currentSSID=", currentSSID);
    WifiConfiguration custom = new WifiConfiguration();
    custom.SSID = getString(R.string.custom);
    adapter.clear();
    adapter.add(custom);
    flushWifiPasswords();
    Log.d(TAG, "#wcs=", wcs == null ? "null" : wcs.size());
    if (wcs != null) {
        int selected = -1;
        for (WifiConfiguration wc : wcs) {
            adapter.add(wc, getWifiPassword(wc));
            Log.d(TAG, "wc.SSID=", wc.SSID);
            if (mFirstLoad && currentSSID != null && currentSSID.equals(wc.SSID)) {
                selected = adapter.getCount() - 1;
                Log.d(TAG, "selected=", selected);
            }
        }
        if (selected > 0) {
            // mFirstLoad == true
            mSpConfigs.setSelection(selected);
        }
        mFirstLoad = false;
    }
}

From source file:com.compal.wifitest.WifiTestCase.java

public boolean saveAPConfig(String mAPType) {
    WifiConfiguration wc = new WifiConfiguration();

    if (mAPType.equalsIgnoreCase(dWpa)) {
        wc.SSID = WpaAPSsid;/*from ww w  .  j a v a2 s  .c  o  m*/
        wc.preSharedKey = WpaAPKey;
        wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
        wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
        wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
        wc.priority = 40; //!!
    }
    if (mAPType.equalsIgnoreCase(dWep)) {
        wc.SSID = WepAPSsid;
        wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
        wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
        wc.wepKeys[0] = WepAPKey; //This is the WEP Password
        wc.wepTxKeyIndex = 0;
    }
    if (mAPType.equalsIgnoreCase(dWpa2)) {
        wc.SSID = Wpa2APSsid;
        wc.preSharedKey = Wpa2APKey;
        wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
        wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
        wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    }
    if (mAPType.equalsIgnoreCase(dShared)) {
        wc.SSID = SharedAPSsid;
        wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
        wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    }
    wc.hiddenSSID = true;
    wc.status = WifiConfiguration.Status.DISABLED;
    wc.priority = 41; //!!

    wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
    wc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
    wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
    wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
    wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
    wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);

    //boolean res1 = mWifiManager.setWifiEnabled(true);
    int res = mWifiManager.addNetwork(wc);
    Log.i(tag, "add" + mAPType + "Network returned " + res);
    boolean es = mWifiManager.saveConfiguration();
    Log.i(tag, mAPType + " saveConfiguration returned " + es);
    boolean b = mWifiManager.enableNetwork(res, true);
    Log.i(tag, mAPType + " enableNetwork returned " + b);

    long startTime = System.currentTimeMillis();
    while ((System.currentTimeMillis() - startTime) < LONG_TIMEOUT * 5) {
        if (mWifiManager.getConnectionInfo().getSupplicantState()
                .equals((SupplicantState) SupplicantState.COMPLETED)
                && !Formatter.formatIpAddress(mWifiManager.getConnectionInfo().getIpAddress())
                        .equalsIgnoreCase("0.0.0.0")) {
            Log.i(tag, Formatter.formatIpAddress(mWifiManager.getConnectionInfo().getIpAddress()));
            Log.i(tag,
                    "getConnectionInfo().getSupplicantState().equals((SupplicantState) SupplicantState.COMPLETED)");
            Log.i(tag, "IP && supplicant state complete = true : " + mAPType);
            return true;
        }
        sleep(100);
    }
    Log.i(tag, "IP || supplicant state complete = false : " + mAPType);
    return false;

}

From source file:de.ub0r.android.wifibarcode.WifiBarcodeActivity.java

/**
 * Add wifi configuration.//from   w  w  w  .  j  av  a  2 s . c  o  m
 */
private void addWifi() {
    WifiConfiguration wc = new WifiConfiguration();
    wc.allowedAuthAlgorithms.clear();
    wc.allowedGroupCiphers.clear();
    wc.allowedKeyManagement.clear();
    wc.allowedPairwiseCiphers.clear();
    wc.allowedProtocols.clear();

    //noinspection ConstantConditions
    wc.SSID = convertToQuotedString(mEtSsid.getText().toString());
    wc.hiddenSSID = true;

    //noinspection ConstantConditions
    String password = mEtPassword.getText().toString();

    switch (mSpNetType.getSelectedItemPosition()) {
    case 1: // WEP
        wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
        wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
        int length = password.length();
        // WEP-40, WEP-104, and 256-bit WEP (WEP-232?)
        if ((length == 10 || length == 26 || length == 58) && password.matches("[0-9A-Fa-f]*")) {
            wc.wepKeys[0] = password;
        } else {
            wc.wepKeys[0] = '"' + password + '"';
        }
        break;
    case 2: // WPA
        wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
        if (password.matches("[0-9A-Fa-f]{64}")) {
            wc.preSharedKey = password;
        } else {
            wc.preSharedKey = '"' + password + '"';
        }
        break;
    default: // OPEN
        wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        break;
    }

    WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
    int netId = wm.addNetwork(wc);
    int msg;
    final boolean ret = wm.saveConfiguration();
    if (ret) {
        wm.enableNetwork(netId, false);
        msg = R.string.wifi_added;
    } else {
        msg = R.string.wifi_failed;
    }
    Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}