Understanding Android Thread, Looper, and Handler

Post date: Aug 20, 2014 8:41:33 PM

This entry is about understanding, from an application developer's perspective, the following Android programming abstractions: Thread, Looper, and Handler.

    Let's start with the simplest. Just like in any modern OS, the Thread abstraction is Android's attempt to capture the powerful multi-tasking idea. In addition, Android makes Thread even more useful by incorporating the Looper abstraction, which is a message/runnable queue, into each Thread. The convenient way to invoke this queue-enabled Thread is the HandlerThread API. 

HandlerThread t = new HandlerThread("My Thread");

There is also the old-fashion way.

Thread t = new Thread(){

@Override

public void run() {

    Looper.prepare();

    Looper.loop();

}}

The queue is essentially a Thread's To-do list, for a Thread will keep handling messages/executing runnable as long as the queue is non-empty, before going to inactive state. 

    Multiple threads running independently is not very interesting. Threads can interact with each other via the Handler interface. Each Handler, upon creation, is attached to a Looper of a Thread.

Looper mLooper = t.getLooper();

Handler mHandler = new Handler(mLooper);

Any thread who has a reference to that Handler becomes a caller thread, and can send message/runnable using the Handler interface for the worker thread to execute.

mHandler.sendMessage(msg);