Search code examples
androidandroid-wifiandroid-5.0-lollipop

WifiConfiguration enable network in Lollipop


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?


Solution

  • 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;
    }