android - 使用什么在后台执行网络操作?

标签 android service android-asynctask broadcastreceiver

我正在从 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 use startService() instead of bindService(). If you wish to interact with a service that is already running, you can use peekService()

这意味着您可以 startService()从广播 rcvr 中,通过 Intent 传递网络操作所需的数据。该服务将执行网络操作。如果服务粘性,可以使用peekService() 。但你永远不应该bindService()到广播 rcvr。

关于android - 使用什么在后台执行网络操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8049221/

相关文章:

java - 为什么不同的 LayoutInflater 会导致不同的 SearchView Icon

android - 在 Mac OS X 上设置 adb

android - Fragments 中的 AsyncTask 执行数据库更新

android - 如何在 android 中创建 nanohttpd 服务器?

android - 如何获取 Android 本地服务实例

image - 将Redmine docker容器部署到应用服务

java - 如何从 Tomcat 8 中的 `HttpServletRequest` 获取服务

java - AsyncTask 不显示 onPreExecute

android - 如何在应用程序开始时获得旋转进度条

android - 如何获得修订号?