Reputation: 31
Fist of all, I manually set up two wifi with my phone, then I use WifiManager.enableNetwork()
I can successfully switch wifi, but after a few seconds, wifi switches back to the previous wifi, what is the reason?
please tell me.
Device: ASUS ZenFone 5 (Android 8.0.0)
Code:
void connectWiFi(String networkSSID) {
int networkId = getNetworkId(networkSSID);
wifiManager.disconnect();
wifiManager.enableNetwork(networkId, true);
wifiManager.reconnect();
}
int getNetworkId(String ssid) {
List<WifiConfiguration> configurations = wifiManager.getConfiguredNetworks();
for (WifiConfiguration config : configurations) {
if (config.SSID != null && config.SSID.equals("\"" + ssid + "\"")) {
return config.networkId;
}
}
return -1;
}
Upvotes: 2
Views: 2978
Reputation: 31
I found the answer.
First, use the broadcast to listen to WiFi disconnect, then use wifiManager.disconnect()
, wait for the broadcast to disconnect, and then use wifiManager.enableNetwork(networkId, true)
.
Upvotes: 1