21

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?

Ollie C
  • 28,313
  • 34
  • 134
  • 217

1 Answers1

13

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.

Community
  • 1
  • 1
hleroy
  • 463
  • 4
  • 10
  • I have a question to @hleroy, so then when shall I start IntentService either OnResume(), OnStart(), or OnClickEventListener() as I need to save locally using SharedPreference for offline use. Say for example I need to list 200 students in UI from server using Webservice ( WCF web api in my case) then where shall I put this line of code ` // start intent service // run Intent Service // Intent downloadIntent = new Intent(this.Context, typeof(StudentIntentService)); //this.Context.StartService(downloadIntent);` – Ishwor Khanal Jul 10 '17 at 01:56