从 IntentService 或 AsyncTask 进行 REST API 调用?
想象一个典型的场景,其中一个活动打开,需要调用 REST HTTP API 来获取一些内容,并且一旦收到就更新 UI。显然,API 调用需要在单独的线程上执行,但应该使用 AsyncTask、IntentService 或其他方法来完成,为什么?
Imagine a typical scenario where an activity opens, needs to call a REST HTTP API to get some content, and once received updates the UI. Obviously the API call needs doing on a separate thread, but should it be done using AsyncTask, an IntentService, or another approach, and why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我建议结合使用
IntentService
和ResultReceiver
,如 这篇文章。另请查看实现此模型的 Google iosched。 2010 版本展示了如何使用
onRetainNonConfigurationInstance
、getLastNonConfigurationInstance
和静态类在配置更改(即屏幕旋转)时保留ResultReceiver
。我已经在应用程序中成功实现了这个模型。如果您对所提供的链接有任何问题,请告诉我。
编辑:我忘记了“为什么”问题;)
AsyncTask
与活动紧密绑定,它无法很好地处理配置更改。它适用于活动生命周期内的短期任务(onResume
和onPause
之间)。我使用HttpClient
进行 REST API 调用,连接超时和套接字超时设置为 20 秒(由于移动网络较差......)。这意味着API调用可以持续长达40秒。您肯定希望在服务中处理如此长的任务,而不是在AsyncTask
中。I would recommend the combination of
IntentService
andResultReceiver
, as described in this post.Also have a look at Google iosched which implements this model. The 2010 version shows how to persist the
ResultReceiver
accross configuration changes (i.e. screen rotation) usingonRetainNonConfigurationInstance
,getLastNonConfigurationInstance
and a static class.I have implemented this model successfully in an application. Let me know if you have any issue with the links provided.
Edit: I forgot the "Why" question ;)
AsyncTask
is tighly bound to the activity and it won't handle well configuration changes. It is fine for short tasks within the activity life (betweenonResume
andonPause
). I'm usingHttpClient
for my REST API calls with connection timeout and socket timeout set to 20s (due to poor mobile network...). It means the API call can last as long as 40s. You definitely want to handle such a long task in a service rather than anAsyncTask
.