Skip to main content

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.

Popular posts from this blog

Android Camera2 API Explained

Compared with the old camera API, the Camera2 API introduced in the L is a lot more complex: more than ten classes are involved, calls (almost always) are asynchronized, plus lots of capture controls and meta data that you feel confused about.

No worries. Let me help you out. Whenever facing a complex system need a little bit effort to understand, I usually turns to the UML class diagram to capture the big picture.

So, here is the class diagram for Camera2 API.

You are encouraged to read this Android document first and then come back to this article, with your questions. I'll expand what is said there, and list the typical steps of using camera2 API. 

1. Start from CameraManager. We use it to iterate all the cameras that are available in the system, each with a designated cameraId. Using the cameraId, we can get the properties of the specified camera device. Those properties are represented by class CameraCharacteristics. Things like "is it front or back camera", "outpu…

Java Collections Framework Cheat Sheet

Java Collections Framework (JCF) implements the Abstract Data Type  for Java platform. Every serious Java programmer should familiar himself on this topic and be able to choose the right class for specific need.  A thorough introduction to JCF is not the target of this small article and to achieve that goal you can start with this excellent tutorial . 

Instead, I'd like to
1) Provide an overview of JCF's classes ,   2) Provide a cheat sheet you can post in your cubicel for daily reference, 3) Underline the relationship between JCF's implementation and the data structure and algorithm you learned in your undergraduate course

With these goals in mind, I came up following diagram - Java Collection Cheat Sheet. You can click it to zoom in. There is no necessity for more explanation once your familiar with UML class diagram and have a basic understanding of common data structures.

Android Security: An Overview Of Application Sandbox

The Problem: Define a policy to control how various clients can access different resources. A solution: Each resource has an owner and belongs to a group.Each client has an owner but can belongs to multiple groups.Each resource has a mode stating the access permissions allowed for its owner, group members and others, respectively. In the context of operating system, or Linux specifically, the resources can be files, sockets, etc; the clients are actually processes; and we have three access permissions:read, write and execute.