Connect with WPA2 encryption
suggest changeThis example adds a WPA/WPA2-PSK network. The app needs ACCESS_WIFI_STATE and CHANGE_WIFI_STATE. reconnect() returns before association finishes, so the method returns true only when that SSID was found and enabled. Do not log preSharedKey. It is the network password.
public boolean ConnectToNetworkWPA(String networkSSID, String password) {
try {
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + networkSSID + "\""; // Please note the quotes. String should contain SSID in quotes
conf.preSharedKey = "\"" + password + "\"";
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);
WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.addNetwork(conf);
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
if (list != null) {
for (WifiConfiguration i : list) {
if (i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
wifiManager.disconnect();
wifiManager.enableNetwork(i.networkId, true);
wifiManager.reconnect();
return true;
}
}
}
return false;
} catch (Exception ex) {
System.out.println(Arrays.toString(ex.getStackTrace()));
return false;
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents