2

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;
}
Vikasdeep Singh
  • 20,983
  • 15
  • 78
  • 104
Ian Tu
  • 31
  • 1
  • 4
  • Probably the other network has not good signal level, and that's why it switches to old one? Your English is OK for me BTW. – Vladyslav Matviienko May 22 '18 at 08:28
  • Thank you for your amendment, wifi signal is very good, manually switch wifi can also be properly connected, but using "WifiManager.enableNetwork()" will have the above problem. – Ian Tu May 22 '18 at 08:52

1 Answers1

1

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).

Ian Tu
  • 31
  • 1
  • 4
  • what can I say, I love you – TootsieRockNRoll Jan 22 '19 at 09:37
  • What do you mean "wait for the broadcast to disconnect"? Can you please add a code sample? – Lance Aug 15 '19 at 12:08
  • @ElJazouli, can you elaborate on how you solved that? The OP hasn't been online for a long time. – Keselme Feb 12 '20 at 15:06
  • @Keselme @Lance it's been soo long since I've done that so I don't quite remember, but if it was me reading this a year ago I would say there is a broadcast receiver that listens for wifi connect/disconnect actions, and then at some point if you want to connect to a wifi you'd need to call `wifiManager.disconnect()` first and once you get the callback on the broadcast receiver then you connect to the desired wifi. – TootsieRockNRoll Feb 18 '20 at 15:48
  • see: https://stackoverflow.com/questions/5888502/how-to-detect-when-wifi-connection-has-been-established-in-android – TootsieRockNRoll Feb 18 '20 at 15:50