Handler vs AsyncTask

My rule of thumb would be:

  • If you are doing something isolated related to UI, for example downloading data to present in a list, go ahead and use AsyncTask.

  • If you are doing multiple repeated tasks, for example downloading multiple images which are to be displayed in ImageViews (like downloading thumbnails) upon download, use a task queue with Handler.


IMO, AsyncTask was written to provide a convenient, easy-to-use way to achieve background processing in Android apps, without worrying too much about the low-level details(threads, message loops etc). It provides callback methods that help to schedule tasks and also to easily update the UI whenever required.

However, it is important to note that when using AsyncTask, a developer is submitting to its limitations, which resulted because of the design decisions that the author of the class took. For e.g. I recently found out that there is a limit to the number of jobs that can be scheduled using AsyncTasks.

Handler is more transparent of the two and probably gives you more freedom; so if you want more control on things you would choose Handler otherwise AsynTask will work just fine.


Always try to avoid using AsyncTask when possible mainly for the following reasons:

  • AsyncTask is not guaranteed to run since there is a ThreadPool base and max size set by the system and if you create too much asynctask they will eventually be destroyed

  • AsyncTask can be automatically terminated, even when running, depending on the activity lifecycle and you have no control over it

  • AsyncTask methods running on the UI Thread, like onPostExecute, could be executed when the Activity it is referring to, is not visible anymore, or is possibly in a different layout state, like after an orientation change.

In conclusion you shouldn't use the UIThread-linked methods of AsyncTask, which is its main advantage!!! Moreover you should only do non critical work on doInBackground. Read this thread for more insights on this problems:

Is AsyncTask really conceptually flawed or am I just missing something?

To conclude try to prefer using IntentServices, HandlerThread or ThreadPoolExecutor instead of AsyncTask when any of the above cited problems ma be a concern for you. Sure it will require more work but your application will be safer.

Tags:

Android