Android Looper MessageQueue and Handler Guts
Friday, March 09, 2012, Modified: Friday, March 09, 2012 Refs

The looper takes over a thread, the main UI thread in the case of an application's main Looper.

* Looper.loop() pulls Messages out of its message queue.
  Each Message has a reference to an associated Handler
  that it is to be given back to (the target member).

* Inside Looper.loop() for each message gotten from the queue:
  * loop() calls public void Handler.dispatchMessage(Message msg)
    using the Handler that is stored in the Message as its target member.
    * If the message has a Runnable callback member, that is run.
    * Else, if the Handler has a shared callback set, that is run.
    * Else, Handler's handleMessage() is called with the Message as an argument.
      (Note, if you subclass Handler as AsyncTask does, you could override
      handleMessage() as it does)
A Handler must be created on the same thread as the Looper that it will send messages to. Its constructor will lookup the current Looper and store it as a member, tying the Handler to that Looper. It will also reference that Looper's message queue directly in its own member. The Handler can be used to send work to the Looper from any thread, but this identity of the message queues routes the work to be done on the Looper's thread.

When we are running some code on another thread and want to send a Runnable to be executed on the UI thread, we could do it like this:
// h is a Handler that we constructed on the UI thread.
public void run_on_ui_thread(final Handler h, final Runnable r)
   // Associate a Message with our Handler and set the Message's
   // callback member to our Runnable:
   final Message message = Message.obtain(h, r);

   // The target is the Handler, so this asks our Handler to put
   // the Message in its message queue, which is the exact same
   // message queue associated with the Looper on the thread on
   // which the Handler was created:

Try Buffer, a smarter way to share links and pictures by spreading your tweets and posts out over time. Sign up from this link and we both get extra features.

Home :: Items