使用什么在后台执行网络操作?
我正在从 BroadcastReceiver
执行网络操作。此操作正在后台执行,发生这种情况时应用程序将不会运行。
使用哪个更好? Service
还是 AsyncTask
?
I am performing a network operation from a BroadcastReceiver
. This operation is being performed in the background and the app will not be running when this happens.
Which is better to use? A Service
or an AsyncTask
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
BroadcastReceiver
对象仅在调用 onReceive() 期间有效。一旦您的代码从此函数返回,系统就会认为该对象已完成并且不再处于活动状态。因此,在这里使用AsyncTask
或Thread
是有意义的。同样来自 文档 :
这意味着您可以从广播 rcvr 中
startService()
传递数据通过意图进行网络操作所需的。该服务将执行网络操作。如果服务是粘性的,您可以使用peekService()
。但绝对不应该bindService()
到广播 rcvr。A
BroadcastReceiver
object is only valid for the duration of the call to onReceive(). Once your code returns from this function, the system considers the object to be finished and no longer active. So it makes sense to just use anAsyncTask
or aThread
here.Also from the documentation :
What this means is you can
startService()
from your broadcast rcvr, pass the data required for your network operation thru an intent. The service will do the network operation. If the service is sticky, you can usepeekService()
. But never should youbindService()
to a Broadcast rcvr.更好地使用服务。 AsyncTask主要是不阻塞UI。
Better use a Service. AsyncTask is mainly not to block UI.