问题描述
我想设计一个应用,显示可用的 Wi-Fi 网络列表并连接到用户选择的任何网络.
I want to design an app which shows a list of Wi-Fi networks available and connect to whichever network is selected by the user.
我已经实现了显示扫描结果的部分.现在我想连接到用户从扫描结果列表中选择的特定网络.
I have implemented the part showing the scan results. Now I want to connect to a particular network selected by the user from the list of scan results.
我该怎么做?
推荐答案
您需要创建 WifiConfiguration
像这样的实例:
You need to create WifiConfiguration
instance like this:
String networkSSID = "test";
String networkPass = "pass";
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = """ + networkSSID + """; // Please note the quotes. String should contain ssid in quotes
然后,对于 WEP 网络,您需要这样做:
Then, for WEP network you need to do this:
conf.wepKeys[0] = """ + networkPass + """;
conf.wepTxKeyIndex = 0;
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
对于 WPA 网络,您需要像这样添加密码:
For WPA network you need to add passphrase like this:
conf.preSharedKey = """+ networkPass +""";
对于开放网络,您需要这样做:
For Open network you need to do this:
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
然后,您需要将其添加到 Android wifi 管理器设置中:
Then, you need to add it to Android wifi manager settings:
WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
wifiManager.addNetwork(conf);
最后,您可能需要启用它,以便 Android 连接到它:
And finally, you might need to enable it, so Android connects to it:
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for( WifiConfiguration i : list ) {
if(i.SSID != null && i.SSID.equals(""" + networkSSID + """)) {
wifiManager.disconnect();
wifiManager.enableNetwork(i.networkId, true);
wifiManager.reconnect();
break;
}
}
UPD:在 WEP 的情况下,如果您的密码是十六进制的,则不需要用引号将其括起来.
UPD: In case of WEP, if your password is in hex, you do not need to surround it with quotes.
这篇关于如何以编程方式连接到 Android 中的特定 Wi-Fi 网络?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!