tags:

views:

678

answers:

3

I'm confused as to when one would choose AsyncTask over a Handler. Say I have some code I want to run every n seconds which will update the UI. Why would I choose one over the other?

+4  A: 

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.

Samuh
+2  A: 

If you want to do a calculation every x seconds, you should probably schedule a Runnable on a Handler (with postDelayed()) and that Runnable should start a thread itself. So the calculation is done every x seconds, but it's executed in another thread. You don't have to pay attention to the delay and you don't have to fear getting an ANR.

MrSnowflake
+4  A: 

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.

alexanderblom