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

14,664

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.

Share:
14,664
Ollie C
Author by

Ollie C

Freelance Android Developer in London SE1, UK. Contact me about your project [email protected] Please note that I ONLY work remotely from my home office. Most projects I take on are shorter, typically one to three months in duration.

Updated on June 06, 2022

Comments

  • Ollie C
    Ollie C almost 2 years

    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?

  • Ishwor Khanal
    Ishwor Khanal almost 7 years
    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);`