Android 6 : Connect to specific wifi network programmatically not working

chimaira picture chimaira · Feb 21, 2016 · Viewed 19.8k times · Source

I am trying to connect to a wifi network by giving the SSID and pass using WifiManager configurations.

Based on this threads solution: How do I connect to a specific Wi-Fi network in Android programmatically?

The reconnect method is called. but nothing happens (not connected).

Is the Android version (6.0.1) for something? If yes then how to perform a network connection programmatically on Android 6?

Answer

Singam picture Singam · Jun 12, 2017

A few things have changed about how you connect to a WiFi network since android Marshmallow. The following code will help you...If you are using Android 6.0 or lowlevel versions...

public void connectToWifi(){
    try{
        WifiManager wifiManager = (WifiManager) super.getSystemService(android.content.Context.WIFI_SERVICE);
        WifiConfiguration wc = new WifiConfiguration();
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        wc.SSID = "\"NETWORK_NAME\"";
        wc.preSharedKey = "\"PASSWORD\"";
        wc.status = WifiConfiguration.Status.ENABLED;
        wc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
        wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);

        wifiManager.setWifiEnabled(true);
        int netId = wifiManager.addNetwork(wc);
        if (netId == -1) {
            netId = getExistingNetworkId(wc.SSID);
        }
        wifiManager.disconnect();
        wifiManager.enableNetwork(netId, true);
        wifiManager.reconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
private int getExistingNetworkId(String SSID) {
    WifiManager wifiManager = (WifiManager) super.getSystemService(Context.WIFI_SERVICE);
    List<WifiConfiguration> configuredNetworks = wifiManager.getConfiguredNetworks();
    if (configuredNetworks != null) {
        for (WifiConfiguration existingConfig : configuredNetworks) {
            if (existingConfig.SSID.equals(SSID)) {
                return existingConfig.networkId;
            }
        }
    }
    return -1;
}

And add permissions in the Manifest file

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />