Android Looper: Communicate with main UI thread via Handlers

Android looper is very good concept for handling various task on same thread. Whole android UI runs on single thread. So how this looper works and what are entities involved in this process.

Four things involved in this process are:

  1. Thread
  2. Looper
  3. Message Queue
  4. Handler


So the story begins with the thread. Once a thread started will be dead after completing its work and wont be usable. If we call Looper.prepare() on that thread then a message queue is associated with that thread.

And when Looper.loop() is called then the looper start looping that message queue. Now whenever new handler instance is created on some thread by calling new Handler() then this handler attach itself to that Thread. Now this handler can post message to the message queue. These messages aggregate on message queue and looper picks these message one by one and pass them to the handler which have posted that message on message queue.

This looper will loop until looper.quit() is called on that thread.

Sample Looper Application

Modify your main layout file res/layout/activity_main.xml as below

In your, We need to create two Handlers. One Handler is associated with main UI thread while other is associated with message queue of another thread.

When we click button, it will send message to background thread handler. I have attached Bundle object with Message to show how we can use Bundle with Message. After sending message to a handler, it is processed in handleMessage(Message). In background thread, we perform some intensive task that should not be performed n main UI thread. After its completion, we sendMessage(Meassage) to  Handler of main UI where it can reflect processing results on main UI. In this example, i have called Looper.quit() in onDestroy() on activity to ensure finishing of loop. Generally, we should have logic with handlers with some particular message so that it process quit().



You may also like...