如何以编程方式扫描、查找和连接到开放的 wifi AP?
Posted
技术标签:
【中文标题】如何以编程方式扫描、查找和连接到开放的 wifi AP?【英文标题】:How to scan, find and connect to an open wifi AP programatically? 【发布时间】:2011-11-25 16:13:33 【问题描述】:我正在开发一个应用程序,它应该自动并定期启用 wifi,扫描网络,过滤掉打开的网络(不需要通过),创建一个 wifiConfiguration 对象并使用它来连接到该网络。
我阅读了有关 android 开发人员的 wifiConfiguration API。在此基础上,我编写了一个启用 wifi、扫描网络并将结果保存在一个列表中的代码示例,如下所示:
11-25 16:05:44.191: I/WIFISCAN(12955): List of networks: [SSID: airlive_w, BSSID: 00:4f:62:2c:96:18, capabilities: [WPA-PSK-CCMP][WPA2-PSK-CCMP][WPS], level: -71, frequency: 2432, SSID: Mikynet, BSSID: 00:1e:2a:ed:62:4e, capabilities: [WPA2-PSK-CCMP], level: -72, frequency: 2427, SSID: TP-LINK_Vectra, BSSID: 74:ea:3a:ab:eb:b0, capabilities: [WPA2-PSK-TKIP+CCMP][WPS], level: -73, frequency: 2462, SSID: Nasza Siec- ryby, BSSID: d8:5d:4c:df:60:74, capabilities: [WPA2-PSK-TKIP+CCMP-preauth], level: -88, frequency: 2437, SSID: lanzarote, BSSID: 00:27:19:f7:05:9c, capabilities: [WPA-PSK-TKIP+CCMP][WPA2-PSK-TKIP+CCMP-preauth], level: -89, frequency: 2437, SSID: Alicja, BSSID: 94:44:52:a7:17:02, capabilities: [WPA-PSK-CCMP][WPA2-PSK-CCMP][WPS], level: -89, frequency: 2442, SSID: orangebox, BSSID: 00:1f:f3:f8:ea:0f, capabilities: [WPA2-PSK-CCMP], level: -89, frequency: 2462]
有了这个结果,我怎么知道其中哪些是开放的(免通行证)? 以及如何为打开的 wifiConfiguration 创建?
这是 WPA-PSK 的示例 wifiConfiguration:
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiConfiguration wc = new WifiConfiguration();
// This is must be quoted according to the documentation
// http://developer.android.com/reference/android/net/wifi/WifiConfiguration.html#SSID
wc.SSID = "\"SSIDName\"";
wc.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);
Log.d("WifiPreference", "add Network returned " + res );
boolean b = wifi.enableNetwork(res, true);
Log.d("WifiPreference", "enableNetwork returned " + b );
我们将不胜感激任何指导! :)
【问题讨论】:
【参考方案1】:据我所知,您可能需要尝试向 Wifi 服务添加开放配置。如果添加开放网络失败,可能需要某种身份验证协议。
WifiConfiguration wc = new WifiConfiguration();
wc.SSID = "some ssid from the list";
wc.status = WifiConfiguration.Status.ENABLED;
wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
int networkId = wifi.addNetwork(wc);
if (networkId == -1)
// probably not open
else
// likely open
您还可以将其与getConfiguredNetworks
方法结合使用,以查看附近是否有任何网络 a) 先前已连接到 b) 是否已打开。
【讨论】:
这个例子对我来说返回“可能打开”用于打开和带有密码的网络。以上是关于如何以编程方式扫描、查找和连接到开放的 wifi AP?的主要内容,如果未能解决你的问题,请参考以下文章
Xamarin表单(ios):以编程方式连接到wifi时的Runtimeexception