Should I use AsyncTask or IntentService for my application?

AndroidGoogle MapsAndroid AsynctaskIntentservice

Android Problem Overview


I have been reading around on internet connectivity with Android and noticed there are different ways to handle this i.e. AsyncTask and IntentService. However, I'm still not sure which one to use. My application is basically a location/trails finder with Google Maps. My internet connectivity will be used to find the nearest trails within a certain radius of the map. So, every time a user moves or swipes the map to a new location then it will update with the nearest trails. It will also add a new trail, and allow the user to rate a trail.

Will AsyncTask suffice for this or should I use IntentService?

Android Solutions


Solution 1 - Android

They can be used very differently for different purposes.

AsyncTask is a handy threading utility that can be used if you need to constantly tell the user something or periodically perform operations on the main thread. It offers a lot of fine-grain control, and because of it's nature is very easy to work with in the Activity whereas an IntentService generally requires using the BroadcastReceiver or IBinder framework.

IntentService can be used very much like an AsyncTask, but it's purpose is meant for background downloading, uploading, or other blocking operations that don't need user interaction or main thread. For example, if you want to download and cache maps, you may want to call an IntentService so the user doesn't have to be looking at the app for it to download. Likewise, if you're sending data to your server, an IntentService is extremely helpful in this regard because you can start and forget. The user can, say, type a comment in your app then press "send". "Send" will launch the IntentService which gets the comment and send it off in to your server on a background thread. The user could press "send" and leave the app immediately and the comment will, eventually, still reach your servers (assuming no errors of course). If you did this with an AsyncTask in your Activity on the other hand, the system could kill off your process in the middle of your exchange and it may-or-may not go through.

Generally speaking, neither are meant for long running applications. They're meant for short, one-off operations. They could be used for permanent, or long-running actions but it's not recommended.

Solution 2 - Android

You should use an AsyncTask for short repetitive tasks that are tightly bound to an activity, like what you're currently trying to do. IntentService are more geared towards scheduled tasks (repetitive or not) that should run on the background, independent of your activity.

Solution 3 - Android

AsyncTask doesn't play well with configuration changes or other things that restart the Activity.

IntentService is good for a something that should always be available, regardless of how long it takes to do its work. I prefer IntentService in most cases because AsyncTask is so much more dependent on Activity state.

Some notes:

  • AsyncTask is best for quick tasks that should go right back to the UI, but it can be used in a variety of situations.
  • The statement "periodically perform operations on the main thread" is vague. AsyncTask spawns a new background thread that is different from the main thread, and does its work on the new thread. Thus the name AsyncTask.
  • An IntentService doesn't require "manipulating" the BroadcastReceiver framework. All you need to do is send a local broadcast Intent, and detect it in your Activity. Whether this is harder to do than an AsyncTask, I don't know.
  • IntentService is meant to do long-running tasks, which it does in the background.
  • AsyncTaskLoader is OK to use, but it's meant to be the base class for CursorLoader, etc. If you want to refresh "nearby" trails when users move to a new location, an IntentService is probably better.

Don't forget to check for connectivity before trying to update location.

Solution 4 - Android

AsyncTasks are very tightly bound to Activitys and can often cause leaked window errors if you navigate away from the Activity that created the AsyncTask. But they are great for showing a ProgressBar because you can quickly update the progress percentage.

IntentServices are cleaner and safer. They are more difficult to implement when you are a beginner Android developer, but once you learn how to start them and handle them you will probably never go back to AsyncTasks!

IntentServices also allow for a more modular design in your app. I typically create a separate class for all my IntentServices, but for AsyncTasks I create them as an Activity inner class. If I were to separate out an AsyncTask from an Activity, I would have to pass in the Activity Context and View objects in the AsyncTask constructor which can be messy.

Solution 5 - Android

As mentioned above AsyncTask will solve your problem.

But Keep in mind that AsyncTask has an important weakness: it doesn't handle well Activity "refresh" (eg during rotation). It may be a problem if, e.g., user rotate the phone while your AsyncTask is still loading stuff. If this is indeed a problem for you I recommend AsyncTaskLoader:

http://developer.android.com/reference/android/content/AsyncTaskLoader.html

Solution 6 - Android

AsyncTask and IntentService have many same

  • Can execute task in worker thread
  • Can run in background
  • Keep running till task finished event the activity which started it is destroyed
  • Can notify to update UI during task running or after task finish
    • For AsyncTask we often use onProgressUpdate, onPostExecute or if you want you can use BroadcastReceiver
    • For IntentService we use BroadcastReceiver
Different
  1. Send task while running or after running finish

Example we have a task is: download file from server base on fileName.

Using AsyncTask

If we one instance of AsyncTask, during execute downloading file A we cannot execute download file B AsyncTask (since we get java.lang.IllegalStateException: Cannot execute task: the task is already running.). Also after downloading file A finished, we can not execute download file B (since we get java.lang.IllegalStateException: Cannot execute task: the task has already been executed (a task can be executed only once).
To download file B during or after download file A, we need to create new instance of AsyncTask.
=> To download file A and file B, we need 2 instance of AsyncTask => 2 worker thread created

Using IntentService

During download file A, we can sent intent to download file B => after download file A finished it will auto start download file B => don't need new instance, don't need new worker thread.

If we sent intent to download file B after download file A finished? After download file A finished, IntentSevice will destroyed (because there is no more task). Therefore, when start download file B, new instance of Service is created however no new thread created (service keep using only 1 worker thread which name is defined in IntentSevice constructor

  1. Implement AsyncTask is easier than IntentService

USING
We will see that AsyncTask and IntentService have many same so in most case we can use AsyncTask or IntentService. However

  • I often use AsyncTask for some task that start, finish, interact with UI in 1 Activity
  • I often use IntentService for some task that can start/finish and interact or don't interact with UI from any Activity

This answer is base on my test. Please correct me if I am wrong. Hope it help.

Solution 7 - Android

In short, AsyncTask is meant for short tasks that have to communicate with main thread. IntentService is meant for long tasks that don't have to communicate with main thread.

For more info, check these links

http://www.onsandroid.com/2011/12/difference-between-android.html

https://medium.com/@skidanolegs/asynctask-vs-intentservice-1-example-without-code-5250bea6bdae

https://android.jlelse.eu/using-intentservice-vs-asynctask-in-android-2fec1b853ff4

Solution 8 - Android

I agree with @DeeV and @ebarrenechea about Intent service in part that you should use it for task that are not tight bound with Activity like uploading some data to server or storing data from server to database.

But starting from Android 3.0 there were introduced Loaders API Which should replace AsyncTask. So for example for loading list which you should display in Activity is better to use Loader which is designed to handle well all the configuration changes and Activity Life-cycle.

Vogella loader tutorial

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohnathan AuView Question on Stackoverflow
Solution 1 - AndroidDeeVView Answer on Stackoverflow
Solution 2 - AndroidebarrenecheaView Answer on Stackoverflow
Solution 3 - AndroidJoe MalinView Answer on Stackoverflow
Solution 4 - AndroidLou MordaView Answer on Stackoverflow
Solution 5 - Androidivan.aguirreView Answer on Stackoverflow
Solution 6 - AndroidLinhView Answer on Stackoverflow
Solution 7 - AndroidHasan El-HefnawyView Answer on Stackoverflow
Solution 8 - AndroidRoman NazarevychView Answer on Stackoverflow