127

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?

Steve
  • 53,375
  • 33
  • 96
  • 141
  • 1
    This has gotten more complicated with AsyncTaskLoaders. See http://stackoverflow.com/q/7120813/969325 for more info. – Warpzit Apr 23 '13 at 16:39

8 Answers8

75

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
  • 36,316
  • 26
  • 109
  • 116
  • That's right. I was using AsyncTasks for all background operations in my project. At some point I started reaching that max jobs limit, so my tasks would only start after another finished. In the end I had to change all my structure to stop using asynctasks and avoid reaching that limitation. – tbraun Feb 08 '13 at 11:57
  • 5
    From Honeycomb on, `AsyncTasks` are executed on one thread, so no parallelism anymore. You still could run them on a paralel `Executor` implementation. – MrSnowflake May 06 '13 at 15:27
63

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
  • 8,632
  • 6
  • 34
  • 40
  • Handler is in the API level 1 & ASYNCTASK in the API level 3. will it be deprecated at any cost? becaz am concentrating on porting applications from older versions to 2.2 & 2.3.. – yokks Feb 03 '11 at 05:39
  • 10
    Neither will be deprecated anytime soon. Handler will never be deprecated as the UI is basically built around it. – alexanderblom Feb 03 '11 at 08:50
  • Shouldn't you use a Loader to load data for your UI to present? – nbarraille May 27 '14 at 16:59
20

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.

Community
  • 1
  • 1
type-a1pha
  • 1,891
  • 13
  • 19
  • Yeah, I've spent a lot of time regretting many uses of AsyncTasks. They seem great, but...so many problems! – SMBiggs Dec 30 '15 at 18:45
  • 6
    I am sorry to so strongly post against your points, but I cannot let your poor style effect noobies to android. Point one. You should NOT have that many threads running. If you come across this your architecture is foobar. Point 2. How on earth.. Okay, yes everything in android is free game to the garbage collector... You would only see abserd behavior as described above, in some strictly task abusive cases. Point 3. Managing your task, not to be rude, is a novice skill. You either kill it when you call onPause, or you properly detach and attach accordingly. – StarWind0 Mar 06 '16 at 03:13
  • 1
    http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html This is all you need to learn how to properly do tasks without the issues above (assuming you aren't doing something like spewing a few hundred tasks) – StarWind0 Mar 06 '16 at 03:20
16

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 in the current UI thread. If you want to start it in another thread, use HandlerThread. AsyncTask is easier to use for us but no better than handler.

沛 晁
  • 3
  • 2
MrSnowflake
  • 4,724
  • 3
  • 29
  • 32
7

The Handler is associated with the application’s main thread. it handles and schedules messages and runnables sent from background threads to the app main thread.

AsyncTask provides a simple method to handle background threads in order to update the UI without blocking it by time consuming operations.

The answer is that both can be used to update the UI from background threads, the difference would be in your execution scenario. You may consider using handler it you want to post delayed messages or send messages to the MessageQueue in a specific order.

You may consider using AsyncTask if you want to exchange parameters (thus updating UI) between the app main thread and background thread in an easy convinient way.

secretlm
  • 2,361
  • 2
  • 27
  • 38
  • 3
    You may create your own Handler associated with another Thread. – Aleksejs Mjaliks Apr 26 '12 at 19:56
  • Handler is not necessarily tied to main thread (UI Thread). It is tied to the thread in which it was instantiated and handles Message's or Runnable's that arrive to this thread message queue. It also can send Message and Runnable objects to this thread message queue. – azec-pdx Dec 23 '14 at 14:59
2

AsyncTask presumes you will do something on the UI thread, after some background work is finished. Also, you can execute it only once (after this, its status is FINISHED and you'll get an exception trying to execute it once more). Also, the flexibility of using it is not much. Yes, you can use THREAD_POOL_EXECUTOR for a parallel execution, but the effort might be not worthy.

Handler doesn't presume anything, except handling Runnables and Messages. Also, it can be run as many times as you wish. You are free to decide to which thread it must be attached to, how it communicates with other handlers, maybe produce them with HandlerThread. So, it's much more flexible and suitable for some repeated work.

Check different kind of Handler examples here.

lomza
  • 9,412
  • 15
  • 70
  • 85
0

They are best interview question which is asked. AsyncTask - They are used to offload of UI thread and do tasks in background. Handlers - Android dosent have direct way of communication between UI and background thread. Handlers must be used to send message or runnable through the message queue.

So AsyncTasks are used where tasks are needed to be executed in background and Handlers are used for communication between a UI and Background Thread.

0

doInBackground - basically does work in another thread. onPostExecute - posts the results on the UI thread and it is internally sending message to handler of main thread. Main UI thread already has a looper and handler associated with it.

So basically,if you have to do some background task,use AsyncTask. But ultimately,if something needs to be updated on UI,it will be using main thread's handler.

Shinoo Goyal
  • 601
  • 8
  • 10