Background

In this post we will see how to use handlers which is another mechanism for asynchronous communication.

NOTE : Both handlers and async task internally use threads. So you can achieve the same functionality by pure java threading.

Using Handlers for async communication in Android

Here is what we are going to do. We are going to simulate a 6 seconds task. After that is completed we will send a message to the handler registered on the main thread and it will show a toast message showing task is completed.

To start with we have a simple layout with a button at the center that says "Start Process"

This is just a class that extends handler and overrides handleMessage method. It then checks whether the message received is of type process completed show toast type. If so them simply show a toast message saying "Finished Processing Task".

In the MainActivitys oncreate method we are getting reference of the button and on its onclick we are starting a new thread that does the processing for 6 seconds and then sends a message to the handler that it is done. We are also creating a new handler here.

NOTE1 : Handler is created on main thread or UI thread so it will have messages corresponding to UI threads message queue.

NOTE2 : You cal also post a runnable to be run on the thread to which handler belongs to.

Simply install the app on your phone or emulator and click on "Start Process" button. You should see the process completed toast after 6 seconds without any ANR.

So in a nutshell -

Handler allows you to send and process Message and Runnable objects
associated with a thread's MessageQueue