4

I want to connect first time wifi network (one not saved before). If I connected to the wifi before, the code below runs well and I access wifi, but if I try first time to connect, nothing happens. 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;
    }
}
Engin
  • 41
  • 5

1 Answers1

0

A bit late, but it might help someone else. You're, kind of, doing it wrong. You're adding a network (the one that hasn't been configured before) and then you try to connect to a configured network (a different one), 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
}

This should suffice. You don't need disconnect/reconnect part.

Goran Devs
  • 332
  • 3
  • 4