Want to understand more about Android UI Thread's Event Queue Want to understand more about Android UI Thread's Event Queue android android

Want to understand more about Android UI Thread's Event Queue


  1. it's a queue with Runnables. The thread calls run(); on each of the runnables.
  2. only threads that called Looper.prepare(), so any thread can potentially have them. There's an Runtime Exception for that "Can't create handler inside thread that has not called Looper.prepare()"
  3. You can't. Stuff is managed by the platform and calls Activity callbacks, Fragment callbacks, dispatch touch events, run animations, run layout, measure and draw. All this in the UI thread.
  4. AFAIK it's a FIFO. But I might be wrong on that one.
  5. Views have a Handler to the UI thread. Handlers are bound to the thread and it's MessageQueue. That's how you can create a new UI thread handler by calling new Handler() on the UI thread. And then post stuff to that thread queue by calling handler.post(Runnable)
  6. I don't believe they're different. But would have to dig on source code to be sure.

It's always helpful to read the docs:

https://developer.android.com/reference/android/os/Handler.html

https://developer.android.com/reference/android/os/MessageQueue.html


It's just a standard message loop, like every GUI platform uses. "Event" is a CS term, not a particular object. Imagine that inside the Android framework you'd see something like this:

MessageQueue queue;void run(){    while(1){        queue.waitForEvent();        Message msg = queue.getEvent();        //Handle msg    }}

Only the UI thread has an event loop, although you could write your own on another thread.

You cannot see the event queue or get a list of events. The ones you need to know about will call some function in your code

Events are executed as soon as the thread can. If there are no events in the queue, the thread sleeps. They should be executed in order, although the framework may cheat on some events.

A message queue and event queue are the same thing. There's also a class called MessageQueue, which is not the same as the queue we're talking about here but which may be used to implement one.