Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android connect to WiFi without human interaction

Tags:

android

wifi

hci

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.

like image 616
Longbiao CHEN Avatar asked May 26 '11 15:05

Longbiao CHEN


2 Answers

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 :

  • SSID string should be surrounded with ", which is denoted by \"
  • addNetwork() method DISABLES the added network by default, so you should enable it with the enableNetwork() method.
like image 173
Longbiao CHEN Avatar answered Sep 20 '22 22:09

Longbiao CHEN


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.

like image 26
Wouter Avatar answered Sep 23 '22 22:09

Wouter