Chapter 8. HandlerThread: A High-Level Queueing Mechanism

Android Message Passing described background execution on a thread using a message queue and dispatch mechanism. The application explicitly coupled the message queue and the dispatch mechanism to a thread. Instead, you can use a HandlerThread, a convenient wrapper that automatically sets up the internal message passing mechanisms.

This chapter covers:

  • How to use the HandlerThread
  • The advantages of HandlerThread compared to manually setting up the message passing mechanism
  • Use cases for the HandlerThread

Fundamentals

HandlerThread is a thread with a message queue that incorporates a Thread, a Looper, and a MessageQueue. It is constructed and started in the same way as a Thread. Once it is started, HandlerThread sets up queuing through a Looper and MessageQueue and then waits for incoming messages to process:

HandlerThread handlerThread = new HandlerThread("HandlerThread");
handlerThread.start();

mHandler = new Handler(handlerThread.getLooper()) {
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        // Process messages here
    }
};

There is only one queue to store messages, so execution is guaranteed to be sequential—and therefore thread safe—but with potentially low throughput, because tasks can be delayed in the queue.

The HandlerThread sets up the Looper internally and prepares the thread for receiving messages. The internal setup gurantees that there is no race condition between creating the Looper and ...

Get Efficient Android Threading now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.