Search code examples
androidandroid-6.0-marshmallowandroid-wifi

WifiManager addNetwork return -1 in Marshmallow


In my application i want to connect to specific wifi connection. My application is working fine till version 19. when install application android 6.0 , addNetwork always return "-1".

Below is the code i am using.

private int configureNetworkAndReturnId() {

    WifiConfiguration config = new WifiConfiguration();
    config.BSSID = "xx:xx:xx:xx:xx:xx";
    config.SSID = "\"" + "Name" + "\"";
    config.priority = 1;
    config.status = WifiConfiguration.Status.ENABLED;
    // Set connection configuration to require encryption
    config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
    config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
    config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
    config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);

    config.preSharedKey = "xxxx";

    final int newId = wifiManager.addNetwork(config);
    Log.d(TAG, "Created new network configuration, ID: " + newId + ", Config: " + config);


    return newId;
}

Since above method is returning -1, when i call boolean isEnabled = wifiManager.enableNetwork(id, true); application is struck .

Anyone faced same issue?


Solution

  • If network id is -1, then read the network id from the existed configured network. If it is available in network list it return the id.

    int newId = wifiManager.addNetwork(config);
            if (newId == -1) {
                // Get existed network id if it is already added to WiFi network
                newId = getExistingNetworkId(SSID);
                Log.d(TAG, "getExistingNetworkId: " + newId);
            }
    
    private int getExistingNetworkId(String SSID) {
        List<WifiConfiguration> configuredNetworks = wifiManager.getConfiguredNetworks();
        if (configuredNetworks != null) {
            for (WifiConfiguration existingConfig : configuredNetworks) {
                if (SSID.equalsIgnoreCase(existingConfig.SSID)) {
                    return existingConfig.networkId;
                }
            }
        }
        return -1;
    }