Android WifiManager making a phantom connection?

亡梦爱人 提交于 2019-12-12 03:41:37

问题


I'm using WifiManager to test for the presence of a particular SSID and verify a given WPA password, but I'm getting a weird result.

The code looks like this:

WifiConfiguration wc = new WifiConfiguration();

// init ssid and password as Strings ...
wc.SSID = "\"" + ssid + "\"";
wc2.preSharedKey  = "\"" + password + "\"";

wc.hiddenSSID = true;
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);

int res = wifi.addNetwork(wc);
boolean b = wifi.enableNetwork(res, true);

The weird part is that enableNetwork() returns true, even if the wifi network with SSID is not online (?!). Note, however, that if the target Wifi network is present and the password is correct, the code successfully makes the connection.

The Android documentation says enableNetwork() "returns true if the operation succeeded." My questions are:

1) How can the network have been enabled if it's not even there?

2) Have I initialized the WifiConfiguration parameter, wc, incorrectly?

3) Is this the right way to make/test a connection to a Wifi network?


回答1:


1) How can the network have been enabled if it's not even there?

The Android documentation says enableNetwork() "returns true if the operation succeeded."

They actually mean that the enabling operation has been successfully initiated, it has't crashed... This could return false if the wifi instance is not linked any more to the wifi supplicant.

2) Have I initialized the WifiConfiguration parameter, wc, incorrectly?

I am not sure, but it looks alright.

3) Is this the right way to make/test a connection to a Wifi network?

Before enabling the network, you should check if the network is actually available by using the startScan() method. (You will get a list of SSID in the callback).

You should also use a BroadcastReceiver to get the result from the Intent action NETWORK_STATE_CHANGED_ACTION, where you could check if your connection to the access point is successful or not.



来源:https://stackoverflow.com/questions/11378452/android-wifimanager-making-a-phantom-connection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!