This is a fairly common requirement. Nearly all types of mobile applications have some sort of background work that has to be done. None of it needs to be done on the same thread as the user interface.
Whether it’s pulling down new information from the server or loading up information into memory, all of it should be done in a background thread. But the big question seems to be which type of background thread should I use?
In Android, accessing the UI elements from a separate thread can create a ton of headaches; so simply creating a standard thread, doing your work, and updating the UI is not enough to do background work.
Background Threading in AndroidLuckily, Android provides several solutions for doing some work in another thread and updating the UI. Both the AsyncTask and the IntentService classes can provide this functionality to the developer with ease. But determining which one should be used for a specific task is harder than you would think. And from my “intensive” research (10 minutes with Google), I don’t see too much differentiating between when to use one or the other.
An AsyncTask allows a simple interface to do some asynchronous work in a separate thread and update the UI.
An IntentService is a basic Android Service that takes a specific Intent, does some work regarding that Intent, and finishes it. Also, an IntentService can take multiple requests, which it does in a sequential fashion by handling one Intent at a time.
The UpshotThe usage between the two really can be answered with one question. Does the background work tie in with one specific activity? An example would be contacting a service to verify login details. If so, you should use an AsyncTask. Otherwise, I suggest going with an IntentService.
When to use AsyncTaskOne thing about AsyncTasks is that they’re directly linked to an Activity, which can either be a bad thing or a good thing – depending on what your trying to do. This means they are also subject to the Operating System’s mercy when it comes to stopping and starting the Activity.
When to use an IntentServiceIf the background work that needs to be done doesn’t really tie to a specific activity, it’s better to use an IntentService. That way it isn’t tied to what the user is doing at one time. The user can close the app or move to another screen, and the background work will still finish in the expected amount of time.
However, one thing to note when using an IntentService is updating the UI from a IntentService can be a bit annoying. First, the IntentService needs to broadcast an intent that contains all of the information the application needs, and then, the application needs to set up a Broadcast Receiver to get the Intent with the new information. This requires adding a new Service in the Android manifest file.
What’s your experience with using Async Tasks and IntentServices?