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:
HandlerThreadcompared to manually setting up the message passing mechanism
HandlerThread is a thread with a message queue that incorporates 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
MessageQueue, and then waits for incoming messages to process.
// 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.
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 ...