Search code examples
androidwifi

How to avoid duplicating of WiFi networks in standard android WiFi list?


In my android app I connect to WiFi network. But, for example, if I connect to this network plenty of times, name of this network appears in standard android WiFi list plenty of times. How can I avoid this?

My code:

String networkSSID = "test"; 
String networkPass = "pass";
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + networkSSID + "\"";  
conf.preSharedKey = "\""+ networkPass +"\"";
WifiManager wifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE); 
wifiManager.addNetwork(conf);

I'll add a screenshot as soon as possible


Solution

  • Don't call addNetwork if the Network already exists! You can find that out by iterating over the getConfiguredNetworksfrom WifiManager.

    If the Network already exists, just connect to it.

    for (WifiConfiguration config : wifiManager.getConfiguredNetworks()) {
       String newSSID = config.SSID;
    
       if (myNetworksSSID.equals(newSSID)) {
          wifiManager.disconnect();
          wifiManager.enableNetwork(config.networkId, true);
          wifiManager.reconnect();
    
         return;
       }
     }
    
     ...
     addNetwork(conf); //your old code