2

I am aware this is most likely a very stupid question, but I just cannot completely understand the point of Handlers. I know the idea is that Handlers execute on the main thread, and they seem to be most commonly used along with worker threads, but why cannot the worker thread just invoke methods on the calling Activity instead of said Activity creating the thread along with a Handler to receive messages?

Again, I apologise for the ignorance of my question, but all I've found online is tutorials on how to use Handlers and my Pro Android 3 book does not clear up my question (or I'm too stupid to understand it properly!)

Or, for that matter, why use them over AsyncTasks, which can modify the UI without problem?

Thank you.

SoManyGoblins
  • 5,605
  • 8
  • 45
  • 65

1 Answers1

5

When using handler (or message) each task becomes "serialized". This has the advantage that there is NO concurrency and therefore no need to lock. It is much easier to make a message driven system stable than an multi-threaded one.

By the way AsyncTask uses Handlers, too

Using handlers directly give you more flexibility. For example you could schedule a message to be send in the future. Or you could abort an scheduled message.

Handlers are a very powerful tool.

stefan bachert
  • 9,413
  • 4
  • 33
  • 40
  • Clearer now. I wasn't aware AsyncTasks used Handlers. So, using an AsyncTask is like a shorthand for writing a specific Handler and using it? – SoManyGoblins Apr 12 '12 at 19:30
  • 1
    AsyncTask abstracts topics like threading, handler, messages, message queues and makes that stuff "invisible" to the developer. It's a comfortable way for executing long time operations outside of UI thread. Using handlers you have "full" control. There are tasks where you may need that – 207 Apr 12 '12 at 19:37
  • 1
    @SoManyGoblins yes, asynctask is just a fancy handler + thread :) and trust me you don't want to mess with concurrent programming :) – Warpzit Apr 12 '12 at 19:37
  • +1 for "It is much easier to make a message driven system stable than an multi-threaded one." So true. – onit Apr 12 '12 at 19:55