我已经在 StackOverflow 上研究了这个问题,但所有答案都指定了如何使用已知的加密算法(主要是WEP)连接到网络。在我的应用程序中,我检索可用的wifi网络列表,并在ListView
中显示它们(使用WifiManager
)。当用户单击列表中的一个项目时,我想连接到网络。
我当前的实现尝试从WifiConfiguration
的功能字符串中获取ScanResult
数据。例如,这些都是检索到的实际功能字符串:
[WPA2-PSK-CCMP][ESS]
[WPA2-PSK-CCMP+TKIP][ESS]
[WPA-PSK-CCMP+TKIP][WPA2-PSK-CCMP+TKIP][ESS]
根据一些研究,我假设这些是支架分离的功能,每个功能的第一项是-
分隔的字符串,显示:
[Authentication Algorithm - Key Management Algorithm - Pairwise Cipher]
我解析这些数据,然后创建一个WifiConfiguration
对象,然后尝试连接到它,但它总是失败(addNetwork
返回-1
)。我究竟做错了什么?这是我的代码:
@Override
public void onItemClick(AdapterView<?> adapter, View parent, int position, long id) {
ScanResult result = (ScanResult) adapter.getItem(position);
WifiConfiguration config = new WifiConfiguration();
String currentNetwork = mWifiManager.getConnectionInfo().getSSID();
if (currentNetwork != null && currentNetwork.equals(result.SSID))
{
Toast.makeText(this, "Already connected", Toast.LENGTH_SHORT).show();
return;
}
config.BSSID = result.BSSID;
config.SSID = result.SSID;
String firstCapabilities = result.capabilities.substring(1, result.capabilities.indexOf("]")-1);
String[] capabilities = firstCapabilities.split("-");
String auth = capabilities[0];
String keyMgmt = capabilities[1];
String pairwiseCipher = capabilities[2];
int a = 0;
if (auth.contains("EAP"))
a |= WifiConfiguration.AuthAlgorithm.LEAP;
else if (auth.contains("WPA"))
a |= WifiConfiguration.AuthAlgorithm.OPEN;
else if (auth.contains("WEP"))
a |= WifiConfiguration.AuthAlgorithm.SHARED;
config.allowedAuthAlgorithms.set(a);
int k = WifiConfiguration.KeyMgmt.NONE;
if (keyMgmt.contains("IEEE802.1X"))
k |= WifiConfiguration.KeyMgmt.IEEE8021X;
else if (auth.contains("WPA") && keyMgmt.contains("EAP"))
k |= WifiConfiguration.KeyMgmt.WPA_EAP;
else if (auth.contains("WPA") && keyMgmt.contains("PSK"))
k |= WifiConfiguration.KeyMgmt.WPA_PSK;
config.allowedKeyManagement.set(k);
int c = WifiConfiguration.PairwiseCipher.NONE;
if (pairwiseCipher.contains("CCMP"))
c |= WifiConfiguration.PairwiseCipher.CCMP;
if (pairwiseCipher.contains("TKIP"))
c |= WifiConfiguration.PairwiseCipher.TKIP;
config.allowedPairwiseCiphers.set(c);
int networkId = mWifiManager.addNetwork(config);
if (networkId == -1)
{
//always hits this line!
Toast.makeText(this, "Failed to create network configuration", Toast.LENGTH_SHORT).show();
}
else
{
//Never reaches here!
mWifiManager.disconnect();
mWifiManager.enableNetwork(networkId, true);
mWifiManager.reconnect();
}
}
答案 0 :(得分:2)
对于WPA *,如果未将preSharedKey设置为8个或更多字符,则将失败并返回-1。我根本没有看到你设置它。