Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a REST API call from an IntentService or an AsyncTask?

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?

like image 502
Ollie C Avatar asked Aug 22 '11 17:08

Ollie C


1 Answers

I would recommend the combination of IntentService and ResultReceiver, 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) using onRetainNonConfigurationInstance, 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 (between onResume and onPause). I'm using HttpClient 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 an AsyncTask.

like image 114
hleroy Avatar answered Oct 22 '22 08:10

hleroy