WifiConfiguration enable network in Lollipop

vintry picture vintry · Nov 18, 2014 · Viewed 8.6k times · Source

I was working on Wifi project, there is a module that enable user to join wifi programatically.

In kitkat and below it's working successfully, but in Lollipop it's not working.

Here is the code :

WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiConfiguration wifiConfiguration = new WifiConfiguration();
wifiConfiguration.SSID = "\"testSSID\"";
wifiConfiguration.hiddenSSID = true;
wifiConfiguration.status = WifiConfiguration.Status.ENABLED;
wifiConfiguration.allowedKeyManagement
.set(WifiConfiguration.KeyMgmt.NONE);
netId = wifiManager.addNetwork(wifiConfiguration);
Log.d("WifiPreference", "add Network returned " + netId);
boolean checkEnableWifi = wifiManager.enableNetwork(netId, true);
Log.d("WifiPreference", "enableNetwork returned " + checkEnableWifi);

my tested device is nexus 5 build number LRX21O, is ther something wrong in my code or bug on Lollipop?

Answer

Santhosh Shettigar picture Santhosh Shettigar · Dec 8, 2014

Faced similar issue on lollipop.

Disabling other networks manually, an then reconnecting wifi manager solved the issue.

boolean enableNework(String ssid, Context cxt) {
    boolean state = false;
    WifiManager wm = (WifiManager) cxt.getSystemService(Context.WIFI_SERVICE);
    if (wm.setWifiEnabled(true)) {
        List<WifiConfiguration> networks = wm.getConfiguredNetworks();
        Iterator<WifiConfiguration> iterator = networks.iterator();
        while (iterator.hasNext()) {
            WifiConfiguration wifiConfig = iterator.next();
            if (wifiConfig.SSID.equals(ssid))
                state = wm.enableNetwork(wifiConfig.networkId, true);
            else
                wm.disableNetwork(wifiConfig.networkId);
        }
        wm.reconnect();
    }
    return state;
}