I'm wondering if there are some code snippets that can be used to connect an Android device to a WiFi network. The network should be either open or WEP/WPA encypted, and visible to that device. Normally, we use GUI interface to input WiFi passwords and tap the connect button. I want to store the password in a place, and use the password to connect to the network seamlessly without human interaction. Is that possible? Thanks a lot.
Thanks guys. With your help, I'm now able to connect to a WPA/PSK encrypted network without pain. Here is my code snippet:
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
// setup a wifi configuration
WifiConfiguration wc = new WifiConfiguration();
wc.SSID = "\"YOUR_SSID\"";
wc.preSharedKey = "\"YOUR_PASSWORD\"";
wc.status = WifiConfiguration.Status.ENABLED;
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
// connect to and enable the connection
int netId = wifiManager.addNetwork(wc);
wifiManager.enableNetwork(netId, true);
wifiManager.setWifiEnabled(true);
The tricks are :
To make OPs sample code work, I had to add one more line:
wc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
Without that line it just won't connect to the network. The configuration is accepted and added, but no connection attempts are made. I actually got the following message in the logcat window:
Event [WPA: Failed to select WPA/RSN] android
which put me to the final solution, figuring out why it didn't work for me.
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