我正在从 BroadcastReceiver
执行网络操作。此操作正在后台执行,发生这种情况时应用程序将不会运行。
哪个更好用? Service
还是 AsyncTask
?
最佳答案
一个BroadcastReceiver
对象仅在调用 onReceive() 期间有效。一旦您的代码从此函数返回,系统就会认为该对象已完成并且不再处于 Activity 状态。因此,仅使用 AsyncTask
是有意义的。或Thread
在这里。
同样来自documentation :
In particular, you may not show a dialog or bind to a service from within a BroadcastReceiver.
If this BroadcastReceiver was launched through a
<receiver>
tag, then the object is no longer alive after returning from this function. This means you should not perform any operations that return a result to you asynchronously -- in particular, for interacting with services, you should usestartService()
instead ofbindService()
. If you wish to interact with a service that is already running, you can usepeekService()
这意味着您可以 startService()
从广播 rcvr 中,通过 Intent 传递网络操作所需的数据。该服务将执行网络操作。如果服务粘性,可以使用peekService()
。但你永远不应该bindService()
到广播 rcvr。
关于android - 使用什么在后台执行网络操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8049221/