Join a WiFi network programmatically in Android

I recently came across a requirement where I need to connect the android device to specific Wifi Networks on request. Here is how i have coded it,

The request will be received through a broadcast

1. Create Wifi Configuration with WifiConfiguration class for the new wifi network.
2. Use wifi manager to disable all other networks except the network that I just added.
3. Now try to connect to an available enabled network. So that the device will connect to the only available enabled network which is the one we added.

Lets go through the code,

WifiConfiguration:

WifiConfiguration wifiConfiguration = new WifiConfiguration();
        wifiConfiguration.SSID = “\”” + networkSSID + “\””;  // This string should have double quotes included while adding.
    wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); // This is for a public network which dont have any authentication

//Add the created wifi configuration to device
        int netId = wifiManager.addNetwork(wifiConfiguration);  //Adds to the list of network and returns the network id which can be used to enable it later.

WifiManager:
WifiManager wifiManager  =(WifiManager)context.getSystemService(Context.WIFI_SERVICE);

       wifiManager.disconnect();
       wifiManager.enableNetwork(netId, true); // Seconds parm instructs to  disableOtherNetworks
       wifiManger.reconnect(); // Now we will connect to the only available enabled network.

Additional Notes:
      WifiManager can switch on your Wi-Fi too. But Incase If you want to switch wifi ON and then do the above, Try to provide few seconds delay (Use thread) for the wifi to switch on before you fire the methods to connect to your network.

To Switch On :  wifiManager.setWifiEnabled(true);
To Switch Off : wifiManager.setWifiEnabled(false);

Thanks to the stack over flow thread here.

Happy Coding, Balachandar KM