暂停服务直至建立互联网连接
我有一项在启动完成后运行的服务。此服务需要互联网连接。等待设备连接到互联网的最佳做法是什么?手机有wifi真的不重要。
我当前的解决方案涉及一个 while 循环,该循环仅检查 ConnectivityManager 直到其中一个网络可用,但这感觉很粗俗。
有更好的方法吗?
I have a service that runs upon boot completion. This service requires internet connectivity. What's the best practice for waiting for the device to connect to the internet? Mobile of wifi doesn't really matter.
My current solution involves a while loop that just checks ConnectivityManager until one of the networks becomes available, but this feels vulgar.
Is there a better way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
确实很粗俗:D
骨架代码:https://stackoverflow.com/a/19968708/281545 - 你的情况更简单,因为你不必唤醒wifi,否则(包括需要很长时间和无线电/CPU 睡眠的情况 - 在这种情况下,简单的意图服务将不起作用)在 2 到 3 之间,您将需要:
2a.服务获取wifi锁
2b.服务调用
reconnect()
、reassociate()
以及所需的任何内容(这可能是特定于设备的)Indeed :D
Skeleton code : https://stackoverflow.com/a/19968708/281545 - your case is simpler as you do not have to wake the wifi, hold wifi locks etc. Otherwise (including the case this takes long and radios/CPU sleep - in which case a simple intent service won't do) between 2 and 3 you would need to :
2a. service acquires a wifi lock
2b. service calls
reconnect()
,reassociate()
and whatever is needed (this may be device specific)您可以使用 BroadcastReceiver:
然后,在代码中的某个位置实例化:
注意:此代码来自 检测3G或Wifi网络恢复
You could use a BroadcastReceiver:
Then, you instantiate somewhere in your code:
Note: this code comes from Detect 3G or Wifi Network restoration