Example usage for android.net.wifi WifiManager addNetwork

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

Introduction

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

Prototype

public int addNetwork(WifiConfiguration config) 

Source Link

Document

Add a new network description to the set of configured networks.

Usage

From source file:Main.java

public static int addNetwork(Context context, WifiConfiguration wifiConfig) {
    setWifiEnable(context, true);/* ww w . j  a  va  2  s  .  c om*/
    WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    int netId = wifi.addNetwork(wifiConfig);
    wifi.saveConfiguration();
    return netId;
}

From source file:com.google.android.apps.iosched.util.WiFiUtils.java

public static void installConferenceWiFi(final Context context) {
    // Create config
    WifiConfiguration config = new WifiConfiguration();
    // Must be in double quotes to tell system this is an ASCII SSID and passphrase.
    config.SSID = String.format("\"%s\"", Config.WIFI_SSID);
    config.preSharedKey = String.format("\"%s\"", Config.WIFI_PASSPHRASE);

    // Store config
    final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    int netId = wifiManager.addNetwork(config);
    if (netId != -1) {
        wifiManager.enableNetwork(netId, false);
        boolean result = wifiManager.saveConfiguration();
        if (!result) {
            Log.e(TAG, "Unknown error while calling WiFiManager.saveConfiguration()");
            Toast.makeText(context, context.getResources().getString(R.string.wifi_install_error_message),
                    Toast.LENGTH_SHORT).show();
        }//w  w w.j a va 2  s  .c  o  m
    } else {
        Log.e(TAG, "Unknown error while calling WiFiManager.addNetwork()");
        Toast.makeText(context, context.getResources().getString(R.string.wifi_install_error_message),
                Toast.LENGTH_SHORT).show();
    }
}

From source file:com.conferenceengineer.android.iosched.util.WiFiUtils.java

public static void installConferenceWiFi(final Context context) {
    // Create config
    WifiConfiguration config = new WifiConfiguration();
    // Must be in double quotes to tell system this is an ASCII SSID and passphrase.
    config.SSID = String.format("\"%s\"", Config.WIFI_SSID);
    config.preSharedKey = String.format("\"%s\"", Config.WIFI_PASSPHRASE);

    // Store config
    final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    int netId = wifiManager.addNetwork(config);
    if (netId != -1) {
        wifiManager.enableNetwork(netId, false);
        boolean result = wifiManager.saveConfiguration();
        if (!result) {
            Log.e(TAG, "Unknown error while calling WiFiManager.saveConfiguration()");
            Toast.makeText(context, context.getResources().getString(R.string.wifi_install_error_message),
                    Toast.LENGTH_SHORT).show();
        } else {//  w  w  w.j  a v  a 2s .c o m
            Toast.makeText(context, context.getResources().getString(R.string.wifi_install_success_message),
                    Toast.LENGTH_SHORT).show();
        }
    } else {
        Log.e(TAG, "Unknown error while calling WiFiManager.addNetwork()");
        Toast.makeText(context, context.getResources().getString(R.string.wifi_install_error_message),
                Toast.LENGTH_SHORT).show();
    }
}

From source file:Main.java

public static boolean connectToNetwork(Context context, String username, String password) {
    boolean status = false;
    try {/* www . ja  v  a 2s  .co m*/
        WifiManager wifi = (WifiManager) context.getSystemService(context.WIFI_SERVICE);

        if (!wifi.isWifiEnabled()) {
            wifi.setWifiEnabled(true);
            Thread.sleep(3000);
        }

        WifiConfiguration netConfig = new WifiConfiguration();
        netConfig.SSID = "\"" + username + "\"";
        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.preSharedKey = "\"" + password + "\"";
        netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
        netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
        netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
        netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);

        int netId = wifi.addNetwork(netConfig);
        status = wifi.enableNetwork(netId, true);
    } catch (Exception e) {
        status = false;
        e.printStackTrace();
    }

    return status;
}

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

/**
 * Add wifi configuration./*from  w  w  w .  j  a v 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();
}

From source file:org.protocoderrunner.apprunner.api.PNetwork.java

@ProtocoderScript
@APIMethod(description = "Connect to a given Wifi network with a given 'wpa', 'wep', 'open' type and a password", example = "")
@APIParam(params = { "ssidName", "type", "password" })
public void connectWifi(String networkSSID, String type, String networkPass) {

    WifiConfiguration conf = new WifiConfiguration();
    conf.SSID = "\"" + networkSSID + "\""; // Please note the quotes. String
    // should contain ssid in quotes

    if (type.equals("wep")) {
        // wep//  w  w w  . j ava2  s  .  com
        conf.wepKeys[0] = "\"" + networkPass + "\"";
        conf.wepTxKeyIndex = 0;
        conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
    } else if (type.equals("wpa")) {
        // wpa
        conf.preSharedKey = "\"" + networkPass + "\"";
    } else if (type.equals("open")) {
        // open
        conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    }

    WifiManager wifiManager = (WifiManager) a.get().getSystemService(Context.WIFI_SERVICE);
    wifiManager.addNetwork(conf);

    List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
    for (WifiConfiguration i : list) {
        if (i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
            wifiManager.disconnect();
            wifiManager.enableNetwork(i.networkId, true);
            wifiManager.reconnect();

            break;
        }
    }

}

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

private void saveWifiConfig() {
    WifiManager wifiManager = (WifiManager) this.getSystemService(WIFI_SERVICE);
    wifiManager.setWifiEnabled(true);//from w  ww.  j a  va 2s. c  o 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;
        }
    }

    // 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:tf.nox.wifisetup.WifiSetup.java

private void saveWifiConfig() {
    WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(WIFI_SERVICE);
    wifiManager.setWifiEnabled(true);/*www .ja v  a2 s.com*/

    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:com.mozilla.SUTAgentAndroid.SUTAgentAndroid.java

public boolean setUpNetwork(String sIniFile) {
    boolean bRet = false;
    int lcv = 0;/*from  w  w w  . ja  va2 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);
}