How To Use Handler In Android

What is a handler? 

 
A Handler allows you to send and process messages and runnable objects associated with a thread's Message queue. A handler instance is associated with a single thread and that thread's message queue. When you create a new handler, it is bound to the thread/ message queue of the thread that is creating it. It will deliver messages and runnables to that message queue and executes them as they come out of the message queue. We need only one handler object per Activity, and there is no need to manually register it.
 
Your background thread can communicate with the handler, which will do all of its work on the Activity's UI thread. In this article, you will learn how to use Handler in Android.
 

Uses of Handler

  1. To schedule messages and runnables to be executed at some point in the future.
  2. To enqueue an action to be performed on a different than your own.
Two options for communicating with the Handler are messages and Runnable objects. 
 

What is a message?

 
Message contains a description and  an arbitrary data object that can be sent to a handler. While the construction of a message is public, the best way to get one of these is to call Message.obtains() or one of the Handler.obtainMessage() method which will pull them from a pool of recycled objects.
 

How to send message objects?

  • sendMessage() put the message in the queue immediately. 
     
  • sendMessageAtFrontOfQueue() puts the messages in the queue immediately and places the message at the front of all the messages. So your message will have the highest priority than other messages.
     
  • sendMessageAtTime() Put the message in the queue at the started time. 
     
  • sendMessageDelayed() put the messages in the queue after a delay, expressed in milliseconds. 
     
  • sendEmptyMessage() send an empty message to the queue
To process these messages the handler needs to implement handlerMessage(), which will be called with each message that appears on the message queue.
 
Here I am going to demonstrate a simple example with Handler in which I have a progressbar in the UI and with a Handler I am updating the progress value of the Progressbar.
 
First I create the main layout and it has a progress bar and a textview, see the code below,
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    
  2. xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent"    
  3. android:layout_height="fill_parent" android:paddingLeft="@dimen/activity_horizontal_margin"    
  4. android:paddingRight="@dimen/activity_horizontal_margin"    
  5. android:background="#BBDD23"    
  6. android:paddingTop="@dimen/activity_vertical_margin"    
  7. android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">    
  8.     
  9. <ProgressBar    
  10. style="?android:attr/progressBarStyleHorizontal"    
  11. android:layout_width="match_parent"    
  12. android:layout_gravity="center_vertical"    
  13. android:max="100"    
  14. android:layout_height="wrap_content"    
  15. android:id="@+id/progressBar"    
  16. android:layout_centerVertical="true"    
  17. android:layout_alignParentLeft="true"    
  18. android:layout_alignParentStart="true" />    
  19. <TextView    
  20. android:layout_width="wrap_content"    
  21. android:id="@+id/textView"    
  22. android:layout_below="@+id/progressBar"    
  23. android:layout_centerHorizontal="true"    
  24. android:layout_height="wrap_content" />    
  25. </RelativeLayout>   
    Now I create a Runnable class named MyThread and in that I have a for loop and this loop will send the progress to handler. see the code below,
    1. class MyThread implements Runnable    
    2. {    
    3.     
    4.     @Override    
    5.     public void run()    
    6.     {    
    7.         for (int i = 0; i < 100; i++)    
    8.         {    
    9.             Message message = Message.obtain();    
    10.             message.arg1 = i;    
    11.             handler.sendMessage(message);    
    12.             try {    
    13.                 Thread.sleep(100);    
    14.             } catch (InterruptedException e)    
    15.             {    
    16.                 e.printStackTrace();    
    17.             }    
    18.         }    
    19.     }    
    20. }   
      Now in the mainActivity class I have the following code to update the UI with progress which i receive from the Thread,
      1. protected void onCreate(Bundle savedInstanceState)    
      2. {    
      3.     super.onCreate(savedInstanceState);    
      4.     setContentView(R.layout.activity_main);    
      5.     progressBar = (ProgressBar) findViewById(R.id.progressBar);    
      6.     textView = (TextView) findViewById(R.id.textView);    
      7.     thread = new Thread(new MyThread());    
      8.     thread.start();    
      9.     handler = new Handler()    
      10.     {    
      11.         @Override    
      12.         public void handleMessage(Message msg)    
      13.         {    
      14.             progressBar.setProgress(msg.arg1);    
      15.             textView.setText("Progress :" + msg.arg1);    
      16.         }    
      17.     };    
      18. }   
      This handle message function will get the progress which sends from the thread and it will update these values to the progress bar and the textview.
       
      Please see the screen shot also.
       
       
      References
       
       
      Read more articles on Android


      Similar Articles