Connecting to a Wi-Fi network programmatically (first ssid access)?

I want to connect a Wi-Fi network for the first time (one of them has not been saved before). If I connected to Wi-Fi before, the code below works fine, and I get Wi-Fi access, but if I try to connect for the first time, nothing will happen. Why is this happening?

String networkSSID = "myssid";
String networkPass = "mypass";
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + networkSSID + "\"";
conf.preSharedKey = "\""+ networkPass +"\"";

WifiManager wifiManager = (WifiManager)MainActivity.this.getSystemService(Context.WIFI_SERVICE);
wifiManager.addNetwork(conf);

List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for( WifiConfiguration i : list ) {
    if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
        wifiManager.disconnect();
        wifiManager.enableNetwork(i.networkId, true);
        wifiManager.reconnect();

        break;
    }
}
+4
source share
1 answer

A little late, but it might help someone else. You kind of do it wrong. You add a network (one that has not been configured before), and then try to connect to the configured network (the other), both with the same SSID. Instead, try this:

netId = wifiManager.addNetwork(conf);
if (netId == -1) {
    netId = //your procedure of getting the netId from wifiManager.getConfiguredNetworks()
}
wifiManager.enableNetwork(netId, true);

In Kotlin, it looks something like this:

var netId = wifiManager.addNetwork(conf)
if (netId == -1) netId = getExistingNetworkId(ssid)
if (!wifiManager.enableNetwork(netId, true)) {
//Handle failure
}

...
private fun getExistingNetworkId(ssid: String): Int {
    wifiManager.configuredNetworks?.let {
        return it.firstOrNull { it.SSID.trim('"') == ssid.trim('"') }?.networkId ?: -1
    }
    //Unable to find proper NetworkId to connect to
    return -1
}

. / .

0

Source: https://habr.com/ru/post/1669832/


All Articles