androidhandlermessage-queuelooper

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


I have checked the official Android documentation/guide for Looper, Handler and MessageQueue . But I couldn't get it. I am new to android, and got very confused with these concepts.


Solution

  • A 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).

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

    Aside from the class docs, there's a nice discussion of all of this here.

    P.S. All the classes mentioned above are in the package android.os.