Search code examples
androidandroid-wifiwifimanagerwifi

Android - creating personal wifi screen


I'm trying to create my own wifi screen where a list of clickable AP is shown to the user. the problem is that when the user click on an AP the device disconnect and then reconnects to the same AP and not the chosen one. Here is the code: (only the open networks part, and I'm trying to move from secured network to an open one)

         public void onClick(View v) {
                WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                List<WifiConfiguration> configuredNetworks = wifiManager.getConfiguredNetworks();
                for (WifiConfiguration configuredNetwork : configuredNetworks) {
                    if (currSSID().equals(configuredNetwork.SSID)) { // I took care of the removel of the "" in configuredNetwork.SSID in my code  
                        configuredNetwork .allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                        wifiManager.disconnect();
                        wifiManager.enableNetwork(configuredNetwork.networkId, true);
                        wifiManager.reconnect();
                        break;
                    }
                }

Solution

  • I ended up using ScanResult instead of WifiConfiguration and created a new configuration - conf with the wanted scan result as follows:

    conf.SSID = "\"" + scanResult.SSID + "\"";
    conf.BSSID = scanResult.BSSID;
    conf.hiddenSSID = true;
    conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    int id = wifiManager.addNetwork(conf);
    wifiManager.disconnect();
    wifiManager.enableNetwork(id, true);
    wifiManager.reconnect();
    wifiManager.saveConfiguration();