Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect to WPA/WPA2 PSK in Android programmatically

trying to connect programmatically from Android to my wireless network.

THe security type is WPA2, encryption AES.

This does not work as expected:

private WifiConfiguration saveWepConfig(String password, String networkSSID) {
        WifiConfiguration conf = new WifiConfiguration();
        conf.SSID = "\"" + networkSSID + "\"";
        // conf.wepKeys[0] = "\"" + password + "\"";
        conf.preSharedKey = "\"" + password + "\"";
        conf.wepTxKeyIndex = 0;
            conf.hiddenSSID = true;
        conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
        conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
        return conf;
    }

Do i have to encrypt the password here? It only saves the connection, does not connect.

like image 617
Gabi Radu Avatar asked Dec 05 '22 08:12

Gabi Radu


2 Answers

Ah...i found the solution right after i posted the question:

    WifiConfiguration conf = new WifiConfiguration();
        conf.SSID = "\"" + networkSSID + "\"";
        conf.preSharedKey = "\"" + password + "\"";
//      conf.hiddenSSID = true;
//      conf.wepTxKeyIndex = 0;
//      conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
//      conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);

        conf.status = WifiConfiguration.Status.ENABLED;        
        conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
        conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
        conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
        conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
        conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
        conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);

It worked for me. Thanks.

like image 77
Gabi Radu Avatar answered Jan 17 '23 18:01

Gabi Radu


You only need to set SSID and preSharedKey. Everything else defaults to WPA/WPA2 (might not be true for really old versions of Android).

public static void saveWpaConfig(Context context, String ssid, String passphrase)
{
    WifiConfiguration wifiConfiguration = new WifiConfiguration();
    wifiConfiguration.SSID = "\"" + ssid + "\"";
    wifiConfiguration.preSharedKey = "\"" + passphrase + "\"";

    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    int networkId = wifiManager.addNetwork(wifiConfiguration);
    if (networkId != -1)
    {
        wifiManager.enableNetwork(networkId, true);
        // Use this to permanently save this network
        // Otherwise, it will disappear after a reboot
        wifiManager.saveConfiguration();
    }
}
like image 34
Harvey Avatar answered Jan 17 '23 17:01

Harvey