I create a wifis list in a range and show it to the user. I want the user to be able to select each of the items in the list and insert a password to connect to the selected SSID.
I wrote this method for connecting wifi:
private WifiConfiguration wifiConf;
private WifiManager wifiMgr;
private WifiInfo wifiInfo;
public boolean connectToSelectedNetwork(String networkSSID, String networkPassword, String securityType) {
int networkId;
int SecurityProtocol;
if (securityType.contains("WEP")) {
SecurityProtocol = 1;
Log.i(TAG, "Security: WEP");
} else if (securityType.contains("WPA2")) {
Log.i(TAG, "Security: WPA2");
SecurityProtocol = 2;
} else if (securityType.contains("WPA")) {
Log.i(TAG, "Security: WPA");
SecurityProtocol = 3;
} else {
Log.i(TAG, "Security: OPEN");
SecurityProtocol = 4;
}
clearWifiConfig();
wifiConf.SSID = "\"" + networkSSID + "\"";
Log.i(TAG, "SSID Received: " + wifiConf.SSID);
switch (SecurityProtocol) {
case WEP:
wifiConf.wepKeys[0] = "\"" + networkPassword + "\"";
wifiConf.wepTxKeyIndex = 0;
wifiConf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
wifiConf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
break;
case WPA2:
wifiConf.preSharedKey = "\"" + networkPassword + "\"";
wifiConf.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
wifiConf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
wifiConf.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wifiConf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wifiConf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
wifiConf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wifiConf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wifiConf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wifiConf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
break;
case WPA:
wifiConf.preSharedKey = "\"" + networkPassword + "\"";
case OPEN_NETWORK:
wifiConf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
break;
}
if ((networkId = wifiMgr.addNetwork(wifiConf)) == -1) {
Log.i("TAG", "Failed to add network configuration!");
return false;
}
if (!disconnectFromWifi()) {
Log.i("TAG", "Failed to disconnect from network!");
return false;
}
if (!wifiMgr.enableNetwork(networkId, true)) {
Log.i("TAG", "Failed to enable network!");
return false;
}
if (!wifiMgr.reconnect()) {
Log.i("TAG", "Failed to connect!");
return false;
}
return true;
}
But when I call this function to connect to the selected Wi-Fi, I always get false! I debugged it many times, and it goes to the first ifin this method AND does not connect to Wi-Fi.
Please help me with your answers. Thank.
Ehsan source
share