Android Concurrent Programming: Looper, Handler and Message

Class Handler is used extensively by Android Applications and framework to achieve concurrent behavior. A typical usage is to allow the worker thread to post an action to be run in the UI thread. Similar C++ constructs, with a little variant, are also widely used by Android native subsystem such as SurfaceFlinger and StageFright to implemented sophisticated concurrent graphic operation and media codec pipeline.

In this article, we will examine the main components that enables this concurrent programming model, in a language neutral way. Let's start with the class diagram: 
Thread, Looper, Handler, Message Class Diagram
A. Each Thread has 0 or 1 Looper.  Not every Thread is born with a Looper. If you need one, call Looper.prepare() and then Looper.loop() in the Thread you want the Looper run in, or use HandlerThread.

Activity's main UI thread already has a Looper created by the framework and it can be retrieved by calling Looper.getMainLooper().

B. Each Looper has exactly 1 MessageQueue. The Looper.loop() keeps polling the MessageQueue and process the Message if any.

C. Handler is the primary user facing class and it is where the customized message handling code goes. It is responsible for creating the message (obtainMessage()), sending the message (sendMessage()) and handling the message(handleMessage()).  Each Handler must be attached to a Looper. When calling sendMessage(), the Message will be sent to the MessageQueue owned by the Handler's Looper.  Handler is the Message producer , while the Looper is the Message consumer.

The most important thing to remember is sendMessage() can be called in any threads but the handler code (i.e handleMessage()) will always be running in the Thread which the Handler's Looper resides in.

D. Multiply Handlers can associate to the same Looper, with each Handler dealing with a particular type of messages. In fact, before you creating a customized Handler to talk to the main thread as described previously, there are already several Handlers[1] created by the framework to deal with system events.

[1] ActivityThread::H() , ViewRootImpl::ViewRootHandler

E. Each Message must have a target Handler, who knows how to handle the message and where to send the Message.  sendToTarget() is actually a handy wrapper to mHandler.sendMessage(this)

Following diagram illustrates the steps of writing a customize Handler in the Main UI Thread and the Message sending/handling flow. Hopefully, the diagram is self explanatory and I won't bother to write more text for it :)
Creating A Customized Handler in Android Main UI Thread and The Message Flow
Actually, the Handler and its relate classes can be considered as an Android implementation of concurrent design pattern called Active Object. Understanding the implementation details can make us more confident when using those utilities, or to certain extend, make us a better programmer.