Looper/Handler API - Part 302 Feb 2017 Android #android #handlers
This 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.
- Data Message
- Task 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.
- arg1, arg2
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
Task message is java.lang.Runnable object which is executed on consumer thread.
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.
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
A message is created in initialized state and populated with data if required. e.g
In pending state, Message is added to MessageQueue for dispatching in consumer thread.
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.
After processing on consumer thread, Looper cleared message state and returns it back to Looper.
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.