如何连接到特定的WIFI网络在Android中编程? [英] How to connect to a specific wifi network in Android programmatically?

查看:144
本文介绍了如何连接到特定的WIFI网络在Android中编程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设计的应用程序,显示无线网络列表提供连接到网络时选择它。我已经实现了部分显示的扫描结果。现在我想连接到由从扫描结果列表中的用户选择一个特定的网络。 谁能告诉我该怎么做呢?

I want to design an app which shows a list of wifi networks available and connect to the network when it is selected. 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. Can anyone please tell me how to do this?

推荐答案

您需要创建这样的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.

这篇关于如何连接到特定的WIFI网络在Android中编程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆