Explanation of Handlers in Android

Explanation of Handlers in Android

Hello everyone, in this article we are going to see What are Handlers and Runnables in android and how can we use them with Java language.

Let's begin.

At the begining of the article first we need to talk on descriptions of these structures.
What is Handler
We can not do operations directly on main process of the program. We use the Handlers to send a process or Message to the main thread queue. When an Handler created defaultly bound with a Looper class. Created handler will send the Message or Process to related bounded Looper Class. In here it will be executed.

We mainly use the Handlers to

  • Update the User Interface from a background thread,
  • Enqueue a task for a different thread
  • Schedule a task for a specified time.

Below image you can see the scgematic of Handlers:

Android Handler Schematic

When you created a handler you can allow the task to be executed as soon as queue is ready or you can specify a delay time to executed. Now make an example on this.

Below code block will show you how to do this:


//Below handler has no delay time, so it will be executed when the message queue is ready.
Handler hndler= new Handler();
     hndler.postDelayed(new Runnable() {
          @Override
          public void run() {
                   Log.d("Log message","This Handler has no delay time.");
          }
});

//Below handler has 5000 miliseconds delay time. It will be executed after this delay time.
Handler hndler= new Handler();
     hndler.postDelayed(new Runnable() {
          @Override
          public void run() {
                   Log.d("Log message","This Handler has 5000 miliseconds delay time.");
          }
},5000);

Also you can perform an operation at background and you can show the process completition via a ProgressDialog with handlers. In this case we are going to use a Thread and a Runnable with Handler.

We first specified a task and how many times we are going to make this task. And then we started our Runnable with overrided run method. We created a for loop with specified repeat count and started to make our tasks with handlers inside this for loop. All of tasks will be queued at the main thread task queue.


       final int progressMaxValue = 100;

       //First initialize a handler
      Handler mHandler =new Handler();
      //And create a progressbar in MainActivity. and set its configurations.
      ProgressDialog mProgressBar = new ProgressDialog(MainActivity.this);
      mProgressBar.setMax(progressMaxValue);
      mProgressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
      mProgressBar.show();

       //Here we created a new thread and Runnable
      new Thread(new Runnable() {
         @Override
         public void run() {
            for (int i = 0; i <= progressMaxValue; i++) {
               final int currentProgres = i;
               //Now update the progressdialog from background Handler
               mHandler.post(new Runnable() {
                  @Override
                  public void run() {
                     //Make some operations here repedatly.
                     mProgressBar.setProgress(currentProgres);
                  }
               });

              //And you can wait for a moment, it is not necessary.
              try {
                  Thread.sleep(500);
               } catch (InterruptedException e) {
                  e.printStackTrace();
               }

            }
         }
      }).start();

Also you can send messages to the handlers. We can process these messages and we can make some operations according to these messages.

Let's see how to send a message to Handlers.

First declare and initialize our Handler and configure it with incoming message. We use Bundle to get message data. Then we get the message via specified key at last we show the message with Toast.

Later we declare a method to send the message to the handler then first declare a Message and Bundle. Then we load the message to the bundle with specified key. Then we send the message to initialized handler. When everything is ready we can call the messageSender method at onCreate or whereever you want, where do you need it.

Below example you will see how to do it.



     private final String message_key = "HandlerMSG";

    //First declare and initialize our Handler and configure it with incoming message.
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            //We use Bundle to get message data.
            Bundle bundle = msg.getData();
            //Then we get the message via specified key
            String msg_str = bundle.getString(message_key);
            Toast.makeText(MainActivity.this, msg_str, Toast.LENGTH_SHORT).show();
        }
    };

    //Here we declare a method to send the message to the handler
    private void sendMessageToHandler(String _msg) {
        //Here we first declare a Message and Bundle
        Message m = new Message();
        Bundle b = new Bundle();
        //Then we load the message to the bundle with specified key
        b.putString(message_key, _msg);
        //And we load the bundle to the Message
        m.setData(b);
        //Then we send the message to initialized handler.
        mHandler .sendMessage(m);
    };

     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_thread_example);
        //We can send the method with a simple method calling like below.
       sendMessageToHandler("thecodeprogram.com");
    }

That is all in this article.

As you can see above we are now good to use Handlers in our android projects.

Have a good handling the background threads.

Burak Hamdi TUFAN


Tags


Share this Post

Send with Whatsapp

Post a Comment

Success! Your comment sent to post. It will be showed after confirmation.
Error! There was an error sending your comment.

Comments

    There is no comment. Be the owner of first comment...