The class Handler can update the UI. A handle provides methods for receiving messages and for runnables. To use a handler you have to subclass it and overide handleMessage () to process messages. To process runables you can use the method post (); you only need one instance of a handler in your activity.

Your thread can post messages via the method sendMessage (Message msg) or sendEmptyMessage.

In this article I am going to explain how to create a handler in an Android application. In this example I will use the class Handler to update a ProgressBar in a background thread.

  •      Start a new project named HandlerDemo.
  •      Open res/values/strings.xml and add the following strings element in the resource tag:
    <string name="startProgress">startProgress</string>
  •    Open res/layout/main.xml and insert the following code:
<?xml  version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android=""
        android:orientation="vertical" android:layout_width="fill_parent"
        <ProgressBar android:id="@+id/progressBar1"
              android:max="10" android:padding="4dip">
        <Button android:text="Start Progress"


·         Now open the Activity file and insert the following code:


import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ProgressBar;

public class HandlerActivity extends Activity {

        private Handler handler;
        private ProgressBar progress;

        public void onCreate(Bundle savedInstanceState) {
               progress = (ProgressBar) findViewById(;
               handler = new Handler();

        public void startProgress(View view) {

              Runnable runnable = new Runnable() {

                      public void run() {
                            for (int i = 0; i <= 10; i++) {
                                   final int value = i;
                                   try {
                                  } catch (InterruptedException e) {
                          Runnable() {

                                          public void run() {
               new Thread(runnable).start();

·         Run the application.

The output looks like below:

Using Handler in Android Application

When you click on the Start Progress button, progress bar will start and looks
like below:

Using Handler in Android Application

  Modified On Mar-23-2018 06:05:30 AM

Leave Comment