Android WifiManager.addNetwork() returns -1

后端 未结 5 500
深忆病人
深忆病人 2020-12-10 10:47

I am writing an android app which will connect to a specific WPA access point, when connected, it will issue a http call. It will not save the network config. I have read al

5条回答
  •  醉酒成梦
    2020-12-10 11:40

    The problem is that you're trying to add the network configuration that already exists. When you call:

    int netId = wifiManager.addNetwork(wc);
    

    it will fail (return -1) if the network configuration with the same SSID already exists. So, what you need to do is to check if netId is -1 and if it is, traverse through the configured networks searching for the network with same SSID and once it's found, return the networkId.

    Kotlin:

    var netId = wifiManager.addNetwork(conf)
    if (netId == -1) netId = wifiManager.configuredNetworks?.let {
        it.firstOrNull { it.SSID.trim('"') == ssid.trim('"') }?.networkId ?: -1
    }
    wifiManager.enableNetwork(netId, true)
    

提交回复
热议问题