O'Reilly logo

Efficient Android Threading by Anders Goransson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required