Ashok Reddy Narra
Ashok Reddy Narra

Reputation: 577

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?

Upvotes: 1

Views: 2002

Answers (2)

Ashok Reddy Narra
Ashok Reddy Narra

Reputation: 577

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;
}

Upvotes: 3

Ajay
Ajay

Reputation: 113

Was the Wifi network you are attempting to connect configured by some other App? You can try forgetting the Wifi network from Settings and then try.

See the Marshmallow release notes. There is a change here that if Wifi was not configured by your App, then it cannot be modified.

Upvotes: 1

Related Questions