Handler

In Android, all application code runs on single thread which is main thread.All UI modifications and handling of input events will be handle by main thread. So when we perform some slow and long running task which block the main thread for a while or may be forever, so to avoid that situation we have to perform long running asynchronously.

Asynchronous task in android perform using thread which will be background thread or worker thread. The results of these async task may need to update UI components. As we cannot access UI components from background thread we need to access main thread(UI Thread) to update UI. So we use the very popular and powerful concepts of android called Handler

Handler allows you communicate back with the UI thread from other background thread. This is useful in android as android doesn’t allow other threads to communicate directly with UI thread.

 
Android Handler and UI Communication

A Handler allows you to send and process Message and Runnable objects associated with a thread’s MessageQueue. Each 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 — from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

Progress Bar Example

Let’s start with an example of how we might use a Handler in an application.

Consider a activity where we have to update ProgressBar and while updating ProgressBar we are updating TextView by using the same Handler.