Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Async Data Loading Methods

Tags:

android

If I need to asynchronously load some data via HTTP (or whatever) in order to update the UI, I have a few options when writing an Android application (among many others that I'm sure I missed):

  1. Use a regular thread and a handler to update the UI.

  2. AsyncTask

  3. Use and IntentService, and use either a callback or broadcast the results via an Intent.

  4. Using Loaders.

From what I understand, an IntentService is not tied to an Activity's lifecycle, so any changes to orientation, etc, will not impact the retrieval of data. Where this is not the case for an AsyncTask or thread fired off within an Activity.

The reason for the question, is that I just recently read about Loaders, and am confused as to their application. They seem to be more closely tied to a data source, where if the data source changes, then "transparently" everything is handled appropriately. Loaders also appear to be tolerant to configuration/orientation changes (I believe).

I've been currently using an IntentService to make RESTful service calls, and broadcasting the results to be received by appropriate Activities.

I'm assuming I could write an HTTP based Loader, but I'm not sure if this is the best use of this mechanism.

What are the advantages/disadvantages to using one of the async data loading methods over any other?

like image 439
Steve Avatar asked Jan 26 '12 13:01

Steve


1 Answers

All of these mechanisms are simply options. There's no such thing as a one size fits all tool and so all of these different methods of completing the same task is a way to cover as many use cases as possible.

Ultimately, it's up to you to decide which method makes more sense for your scenario. But for a sort of generic explanation of what you should use...

  1. Regular thread and a handler - Why when there are other, simpler, options?

  2. AsyncTask - Since an AsyncTask will almost always depend on an Activity, use this when you need to load data asynchronously and you are 100% certain of how long it may take. Example: Executing an SQLite query.

  3. IntentService/Service - Services are not bound to an Activity like an AsyncTask is, therefore, they are perfect for scenarios in which you may not know how long it will take to complete. Example: Downloading data from a web API and updating a database.

  4. Loaders - Loaders are aimed at simplifying the process of loading data and populating it into UI. The nature of Loaders sort of assumes that the data you will be loading will be presented to the user as a list of some sort. Example: Downloading data and populating it into a ListView

like image 116
Alex Fu Avatar answered Sep 23 '22 08:09

Alex Fu