Android-以编程方式连接到wifi [英] Android - connect to wifi programmatically

查看:92
本文介绍了Android-以编程方式连接到wifi的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以编程方式连接到WiFi网络.

I would like to connect to WiFi network programmatically.

这是我的代码:

wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);

WifiConfiguration config = new WifiConfiguration();
config.SSID = "\"" + ssid + "\"";
config.preSharedKey = "\""+ key +"\"";

int netId = wifiManager.addNetwork(config);
wifiManager.saveConfiguration();
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();

当我在手机上启用wifi时,它可以按预期工作,但是问题是禁用wifi时.在这种情况下,唯一的结果是启用wifi适配器,但未连接到网络.启用似乎需要花费很长时间,因此它将无法连接.对我来说,另一个奇怪的事情是 wifiManager.getConfiguredNetworks()返回null.你知道如何解决这个问题吗?

When I have wifi enabled on my phone, it works as expected, but the problem is, when wifi is disabled. In this case the only result is enabling wifi adapter, but not connecting to the network. It seems like enabling takes to long so it won't get connected. Another strange thing to me is that wifiManager.getConfiguredNetworks() returns null. Do you know how to fix that?

谢谢

推荐答案

启用似乎需要很长时间,因此无法连接.

It seems like enabling takes to long so it won't get connected.

是的.这是因为网络的启用是异步完成的,它是并行发生的,并且不会立即发生.这是您的问题的两种可能的解决方案:

Yes. This is because enabling of the network is done async, it happens in parallel, and doesn't occur immediately. Here are two possible solutions to your problem:

1)这是最简单的解决方案,但不是最佳解决方案.如另一个用户所描述的那样,在循环中检查是否要输入扫描结果.但是,您应该在循环的每个循环之间添加某种形式的睡眠.IE.您要等待1毫秒,以免耗尽所有CPU资源.我不确定如何在Android中做到这一点.这种方法还有另一个问题.如果u在GUI线程中,则在等待建立连接时,将以这种方式阻止所有GUI事件.

1) This is the easiest solution, but not the best. Loop as described by another user checking for the scan results to come in. However, you should add a sleep of some sort between every cycle of the loop. I.E. you want to wait for 1ms, so as to not eat up all the CPU resources. I am not sure how to do this in Android off the top of my head. There is another problem with this method. If u are in the GUI thread, you will block all GUI events this way, as you wait for the connection to be established.

2)这是正确的解决方案.建立网络连接后,您可以注册广播事件.然后,您将在事件结束时得到一个事件.从此事件中,您可以完成执行所需的任何操作.

2) This is the proper solution. You can register for broadcast events after the network connection has been established. Then you will get an event when it finishes. From this event you can finish performing whatever operations are needed.

抱歉,我们急切地回答了这个问题.我不是Android专业人士,所以我无法从头开始解释如何执行此操作的详细信息,但我认为我至少会为您指明正确的方向.

Sorry for the rushed answer. I am not an Android pro, so I can't explain the details as to how to do this off the top of my head, but I thought I would at least point you in the right direction.

这篇关于Android-以编程方式连接到wifi的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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