Looper/Handler API - Part 3

This is part 3 of looper/handler API series

In part 1 and 2, we had skimmed through the API and created an example app. In this part, we will study in detail Message and its types.

Objects inserted in MessageQueue of the Looper are of Message type. There are two types of messages.

  • Data Message
  • Task Message

Data Message

A data message consists of some data to be passed to handler. It has a number of fields which can be used to pass data. e.g.

  • what
  • arg1, arg2
  • object
Message m = Message.obtain(Handler h);
Message m = Message.obtain(Handler h, int what);
Message m = Message.obtain(Handler h, int what, Object o);
Message m = Message.obtain(Handler h, int what, int arg1, int arg2);
Message m = Message.obtain(Handler h, int what, int arg1, int arg2, Object o);
 

Although, you can obtain message directly from Message.obtain method but Handler also provides wrapper around these methods and returns message with handler set to this handler.

workerThread.getHandler().obtainMessage(what);

Task Message

Task message is java.lang.Runnable object which is executed on consumer thread.

     workerThread.getHandler().post(new Runnable() {
                @Override
                public void run() {
                    // post task
                }
            });

Explanation

A message queue can contain any number of data and task messages. Data messages are dispatched to Handler callback while task messages are run on consumer thread without calling handler callbacks.

Message Lifecycle

Android stores Messages in application wide pool and reuses them when necessary. At given time, a Message can be in one of the following states

  • Initialized
  • Pending
  • Dispatched
  • Recycled

Initialized

A message is created in initialized state and populated with data if required. e.g

Message m = Message.obtain();

Pending

In pending state, Message is added to MessageQueue for dispatching in consumer thread.

Dispatched

In dispatched state, Message is dispatched to consumer thread for processing. As Message contains information about its Handler, Looper dispatches Message to its related Handler.

Recycled

After processing on consumer thread, Looper cleared message state and returns it back to Looper.

created
created
initialized
initialized
pending
pending
dispatced
dispatced
recycled
recycled

Caution!

Looper API does not provide any callbacks for observing the states of message and we can not assume the message state, therefore you should never change the state of Message after it is pushed to the MessageQueue.

It is possible that we will be changing the state of a Message after it is dispatched or being reused after recycling.

top