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
HandlerThreadcompared 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:
HandlerThreadhandlerThread=newHandlerThread("HandlerThread");handlerThread.start();mHandler=newHandler(handlerThread.getLooper()){@OverridepublicvoidhandleMessage(Messagemsg){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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access