Search code examples
androidwifimanagerandroid-connectivitymanager

WifiManager enableNetwork reverts to previous network after a few seconds


On Android 8.1.0 and above, I am coming up against a major issue. When connecting to a network with no internet using enableNetwork, Android decides after a few seconds to put the device back on the previous network.

I have intentionally connected to the network desired and am planning to use bindToNetwork to ensure that all traffic goes through the network, however Android appears to be ignoring the bind and simply disconnecting very quickly afterwards.

I have seen a few permutations of this question being asked here, all with no replies, unfortunately.

I am creating an connecting to the network with the following code. I am able to see the network connecting.

WifiConfiguration conf = new WifiConfiguration();
conf.SSID = desiredSSID;
if (desiredNetwork.has("password")) {
    conf.preSharedKey = String.format("\"%s\"", desiredNetwork.get("password"));
}
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);

int networkID = wifiManager.addNetwork(conf);
wifiManager.enableNetwork(networkID, true);

Is there an available option to disable this behaviour, as I intentionally connecting to a network with no internet available.

Thanks.


Solution

  • I was able to resolve this issue by removing the existing config from the configured wifi list. The network will not disconnect from a new config.

    List<WifiConfiguration> wifiConfigurationList = wifiManager.getConfiguredNetworks();
    
    for (WifiConfiguration removeConfig : wifiConfigurationList) {
        if (removeConfig.SSID.equals(desiredSSID)) {
            wifiManager.removeNetwork(removeConfig.networkId);
            break;
        }
    }
    

    Simply adding the network again, as above fixes the issue.