Android wifi starts after reconnecting the previous hotspot via wifimanager
In my application, I connect to a wifi hotspot using wifiManager using the call described in the docs that tell you to call enableNetwork and pass true as the second parameter to disable other networks:
wifiManager.enableNetwork(networkId, true);
A side effect is that after disconnecting from the hotspot, the network I was previously connected to is still disconnected. If you look in the wifi settings, it will be listed as "Disabled".
I would like to leave the state of the previously connected network as I found it. To do this, I save the state of the configured networks before adding my new network, and then restore the allowed states after disconnecting from the new network:
private void saveWifiState() {
final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
wasWifiEnabled = wifiManager.isWifiEnabled();
savedNetworks = wifiManager.getConfiguredNetworks();
}
private void restoreSavedWifiState() {
final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if (!wasWifiEnabled) {
wifiManager.setWifiEnabled(false);
}
// When we connected to the specified network we disabled all others.
// Now restore the enabled state for those that were previously enabled.
if (savedNetworks != null) {
for (int i = 0; i < savedNetworks.size(); ++i) {
if (savedNetworks.get(i).status == WifiConfiguration.Status.CURRENT ||
savedNetworks.get(i).status == WifiConfiguration.Status.ENABLED) {
wifiManager.enableNetwork(savedNetworks.get(i).networkId, false);
}
}
}
}
}
public void disconnect()
{
final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
wifiManager.removeNetwork(networkId);
restoreSavedWifiState();
wifiManager.saveConfiguration();
}
When I run this code on a Samsung Galaxy Tab 4 10.1 (SM-T531) running Android 4.4.2, it leaves the wifi in a bad state. Scanning for AP stops working. I get "Requested scan (ret = -16) - timeout 30 seconds" followed by "Failed to start AP scan" from wpa_supplicant in logcat.
If I connect to the wifi settings and try to connect the network from which I was originally connected using the saved password, it fails with the "CTRL-EVENT-ASSOC-REJECT" message from wpa_supplicant in logcat. I have to reboot or turn on / off airplane mode in order to reconnect to this network.
Any ideas on why the call enable network feature puts wifi in a bad state? Is there a better way to keep the original state of the inclusion of other networks?
source to share
No one has answered this question yet
Check out similar questions: