I want to design an app which shows a list of Wi-Fi networks available and connect to whichever network is selected by the user.
I have implemented the part showing the scan results. Now I want to connect to a particular network selected by the user from the list of scan results.
How do I do this?
You need to create WifiConfiguration
instance like this:
String networkSSID = "test";
String networkPass = "pass";
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + networkSSID + "\""; // Please note the quotes. String should contain ssid in quotes
Then, for WEP network you need to do this:
conf.wepKeys[0] = "\"" + networkPass + "\"";
conf.wepTxKeyIndex = 0;
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
For WPA network you need to add passphrase like this:
conf.preSharedKey = "\""+ networkPass +"\"";
For Open network you need to do this:
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
Then, you need to add it to Android wifi manager settings:
WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
wifiManager.addNetwork(conf);
And finally, you might need to enable it, so Android connects to it:
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;
}
}
UPD: In case of WEP, if your password is in hex, you do not need to surround it with quotes.