Android connect to WiFi without human interaction

Felix Chan picture Felix Chan · May 26, 2011 · Viewed 18.1k times · Source

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.

Answer

Felix Chan picture Felix Chan · May 27, 2011

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.