Example usage for android.net.wifi WifiManager enableNetwork

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

Introduction

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

Prototype

public boolean enableNetwork(int netId, boolean attemptConnect) 

Source Link

Document

Allow a previously configured network to be associated with.

Usage

From source file:Main.java

public static void reconnectWifi(Context context, int networkId) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    if (ni != null) {
        WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (networkId > -1) {
            wm.enableNetwork(networkId, true);
        }/*  www. j  av  a 2s .co  m*/
    }
}

From source file:Main.java

public static void enableNetwork(Context context, int networkid) {
    WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    // wifi.updateNetwork(wifiConfig);
    wifi.enableNetwork(networkid, true);
    wifi.saveConfiguration();/*from   w  w  w  .  j  a v a  2 s  .c  o m*/
}

From source file:Main.java

/**
 * Requires {@link android.Manifest.permission#ACCESS_WIFI_STATE}
 * and {@link android.Manifest.permission#CHANGE_WIFI_STATE} permissions.
 *
 * @param context/*from   w  w  w  .jav a2  s  .  c  o m*/
 * @return
 */
@SuppressLint("MissingPermission")
public static void reconnectWifi(Context context, int networkId) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    if (ni != null) {
        WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (networkId > -1) {
            wm.enableNetwork(networkId, true);
        }
    }
}

From source file:Main.java

public static void connectionWifi(Context context, WifiConfiguration wifiConfig, int ntind,
        boolean wantConnection) {
    WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    // wifi.saveConfiguration();
    wifi.updateNetwork(wifiConfig);/*  w w w  . j a v a2  s  .  co  m*/
    wifi.enableNetwork(ntind, wantConnection);
}

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();
        }/*from   w  w w . j a  v  a2  s.co  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 {/*from ww w . j  a  v  a 2s.  com*/
            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 {//from  w ww . ja v a2  s .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 om*/
 */
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//from w ww . j  av a  2 s.c om
        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);// w w  w. j a va  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;
        }
    }

    // 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();

}