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?
Open Settings. Click on Network & Internet and choose WiFi. Scroll down and tap WiFi Preferences. Select Turn on WiFi automatically.
This post shows steps to programmatically connect your app to wifi. We will use Wifi Manager to manage wi-fi connectivity and Connectivity Manager to handle network state and connectivity changes. First and foremost, add permissions in your manifest file.
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.
The earlier answer works, but the solution can actually be simpler. Looping through the configured networks list is not required as you get the network id when you add the network through the WifiManager.
So the complete, simplified solution would look something like this:
WifiConfiguration wifiConfig = new WifiConfiguration(); wifiConfig.SSID = String.format("\"%s\"", ssid); wifiConfig.preSharedKey = String.format("\"%s\"", key); WifiManager wifiManager = (WifiManager)getSystemService(WIFI_SERVICE); //remember id int netId = wifiManager.addNetwork(wifiConfig); wifiManager.disconnect(); wifiManager.enableNetwork(netId, true); wifiManager.reconnect();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With