In Android, thread communication is trivial unless it involves UI thread. Care must be taken when communicating with UI thread, because blocking UI thread can effect you user’s experience badly.
Many high level threading APIs in java are not well suited for communication with UI thread because of their blocking nature. e.g. BlockingQueue. To overcome these issues, Android has come up with it’s own message passing mechanism.
Looper/Handler API in Android is specific implementation of Consumer-Producer problem (also known as bounded-buffer) in which Producer never blocks. The producer puts the tasks in the queue and consumer consumes them on appropriate time.
Classes
Looper
Looper associates a Message Queue with the thread. Later, this queue will be utilized by Handler and Looper
Handler
Handler is a two way interface. In producer thread, it inserts messages in the queue while in consumer thread it consumes those messages.
Message Queue
Message Queue is an unbounded linked list attached with looper. It contains object of type Message. Looper will loop through this queue and pass messages to handler.
Message
Message defines a message containing a description and arbitrary data object that can be sent to a Handler.
Relationship
Example
Just to understand how every component fits together, let’s write a simple app which does a long running operation when a button is
clicked.
We will write a Worker Thread which will do some long running operation in background when a message is received. On the main thread,
we will add message to the MessageQueue using handler.
I am writing code for this example here. In next article I will explain how it works.
Worker Thread
Main/Launcher Activity
MainActivity Layout
Output (after clicking Do Something button many times, Log message are specially crafted for this example, see source code for better understanding)
Please don’t use this code in production, it is not thread safe, I have written here just give you an idea about how it works.