Android 6.0 made some changes to the WiFi behavior and it breaks my app behavior and cannot find a solution for it.
Basically, for Android 6.0 you are not permitted to modify or delete WifiConfiguration objects that are not created by your app. This means I need to always create my own WifiConfiguration objects. However, if there is already a WifiConfiguration for a particular AP made by the user or other app, I cannot create another one for that AP.
wifiManager.addNetwork(wifiConfiguration) returns -1. This works on all previous Android versions but not on Android 6.0
So I am stuck. Is this an Android bug? I imagine a lot of developers should suffer from this if they develop apps for custom hardware that has its own WiFi access point.
Yes. It is an Android 6.0. bug and it seems it will be fixed in a new version.
https://code.google.com/p/android/issues/detail?id=192622
I think it helps....A few changes needed...
WifiConfiguration objects that are not created by your app for every time. The app doesnt have permission to create another object...So we need connected with previous existing netID.
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.RSN);
wc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wifiManager.setWifiEnabled(true);
int netId = wifiManager.addNetwork(wc);
if (netId == -1) {
netId = getExistingNetworkId(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 Manifest file also...