且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android-以编程方式连接到wifi

更新时间:2021-06-27 22:14:04

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

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.