What is the relationship between Looper, Handler and MessageQueue in Android?

Technology CommunityCategory: AndroidWhat is the relationship between Looper, Handler and MessageQueue in Android?
VietMX Staff asked 3 years ago

Looper is a message handling loop: it reads and processes items from a MessageQueue. The Looper class is usually used in conjunction with a HandlerThread (a subclass of Thread).

Handler is a utility class that facilitates interacting with a Looper—mainly by posting messages and Runnable objects to the thread’s MessageQueue. When a Handler is created, it is bound to a specific Looper (and associated thread and message queue).

In typical usage, you create and start a HandlerThread, then create a Handler object (or objects) by which other threads can interact with the HandlerThread instance. The Handler must be created while running on the HandlerThread, although once created there is no restriction on what threads can use the Handler‘s scheduling methods (post(Runnable), etc.)

The main thread (a.k.a. UI thread) in an Android application is set up as a handler thread before your application instance is created.