Looper/Handler API - Part 3
Android #android #handlersThis is part 3 of looper/handler API series
- Looper/Handler API - Part 1
- Looper/Handler API - Part 2
- Looper/Handler API - Part 3
- Looper/Handler API - Part 4
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
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.
Task Message
Task message is java.lang.Runnable object which is executed on consumer thread.
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
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.
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.