Search code examples
androidwifiandroid-wifi

How to forget wifi which it does not aviable right now?


I want to forget wifi network with this code sample but it cannot forget wifi which not in range.

private void removeNetwork(WifiManager wifiManager, WifiConfiguration wc) {
        if (!wifiManager.isWifiEnabled()) enableWifi();
        int id = wifiManager.addNetwork(wc);
        wifiManager.enableNetwork(id, true);
        wifiManager.removeNetwork(id);
        wifiManager.saveConfiguration();
    }

How I can remove network?

UPD1:

I'm talking about the WIFI information which was added by myself.

private void addNetwork(WifiManager wifiManager, WifiConfiguration wc) {
    if (!wifiManager.isWifiEnabled()) enableWifi();
    int id = wifiManager.addNetwork(wc);
    wifiManager.disconnect();
    wifiManager.enableNetwork(id, true);
    wifiManager.reconnect();
    wifiManager.saveConfiguration();
}

Solution

  • I tested this code example and code work well, something wrong with your implementation of this code.

    It is depend of wifi configuration and this is my work example.

    private void WPA(String networkSSID, String networkPass, WifiManager wifiManager, String command) {
            WifiConfiguration wc = new WifiConfiguration();
            wc.SSID = "\"" + networkSSID + "\"";
            wc.preSharedKey = "\"" + networkPass + "\"";
            wc.status = WifiConfiguration.Status.ENABLED;
            wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
            if (command.equals("add")) {
                addNetwork(wifiManager, wc);
            }else  if (command.equals("remove")) {
                removeNetwork(wifiManager,wc);
            }
        }