当应用程序在 AsyncTask 执行期间进入后台时,它应该做什么?
我有一个使用 AsyncTasks 调用 REST 服务器的应用程序。
想象一下,在加载期间(即 AsyncTask 访问 REST 服务器并将数据发送到下一个屏幕),用户按 Home 键。
建议:
- 取消当前 AsyncTask 并在恢复 Activity 时重新启动
,或者
- 继续 AsyncTasks 但通过检查应用程序是否在后台来避免 startActivity(以避免将应用程序发送到后台后新 Activity 的前台)。 onResume 发送到下一个活动
您应该预见的最坏情况:
- 应用程序进入后台并由于内存不足而被终止
- 异步任务由于超时或其他 REST 错误而
失败 两者之后,用户返回到应用程序。 。
I have an application that uses AsyncTasks to make calls to a REST server.
Imagine that during a loading period (this is, the AsyncTask going to the REST server and gets data to the next screen) the user presses Home.
What is recommended:
- Cancel the current AsyncTask(s) and restart when resuming the Activity
or
- Continue the AsyncTasks but avoiding the startActivity by checking if the app is on background (to avoid the foreground of the new activity after sending the app to background). And onResume sending to the next activity
Worst case scenarios that you should foresee:
- The app goes to background and is killed due to lack of memory
- The asynctask fails due to timeout or other REST error
After both, the user goes back to the app...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(4)
在配置更改期间使用 AsyncTasks 可能会变得非常混乱。根据个人经验,我建议采用 IntentService/ResultReceiver 路线。
有关详细信息,请参阅此帖子:
我想您想知道的是从用户的角度来看哪种方式更好。根据我的经验,用户希望应用程序在后台继续下载,因为如果他按主页,他通常要么想检查中间的一些其他应用程序,要么他无意中按下了它并希望尽快返回到您的应用程序可能的。如果用户想要取消下载,他通常会按后退按钮或应用程序屏幕上某处的特定按钮来取消下载。因此,当用户通常希望继续使用该应用程序时,您的应用程序更方便的行为是继续下载数据,并希望在用户返回您的应用程序时已经向用户显示下载的数据。
从技术角度来看,我不会使用服务。我会让 AsyncTask 继续运行。在最坏的情况下,当应用程序在中间被杀死时,当用户返回应用程序时,应用程序会自动进入启动活动,因为应用程序无论如何都会重新启动。如果异步任务失败,您可以检查数据是否已成功下载,以及是否未显示正在启动的活动。您可以通过将下载的数据存储在初始值为空的变量中来轻松实现此目的。如果下载后变量仍然为空,则 AsyncTask 失败,您必须进入启动活动。我认为这是一个非常强大的实现。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
好吧,我会推荐应该使用 AsyncTask 来完成其工作的 Service。服务将使您的活动免受方向变化或用户退出的影响。 AsycnTask 将隔离 UI 线程被阻塞的情况。但请确保在使用完 REST api 后退出服务。
这将为您带来两全其美的效果。另外,如果您不使用数据库作为本地缓存,那么您也可以尝试这样做。因此,即使用户离开,该服务也会将获取的数据存储在数据库中,当用户回来时,您可以快速显示屏幕。
编辑:只想添加 IntentService 很容易实现。
请尝试 Google 的 Android 上的 REST 客户端设计模式,了解更详尽的说明
Well I ll recommend Service which should use AsyncTask to do its work. Service will insulate your activity from orientation change or user exiting. AsycnTask will insulate from the UI thread being blocked. But do make sure to exit Service when you are done with REST api.
This will give you best of both. Also if you are not using DB as a local cache then you can try that too. So even if the user goes away, the service will store the fetched data in the DB and when the user comes back you can quickly display the screen.
EDIT: Just want to add IntentService are easy to implement.
Try Design Patterns for REST clients on Android by Google for more exhaustive explanation