What is Handler and what is it used for?

Technology CommunityCategory: AndroidWhat is Handler and what is it used for?
VietMX Staff asked 3 years ago

When we install an application in Android, then it creates a thread for that application called MAIN UI Thread. All activities run inside that thread. By the android single thread model rule, we can not access UI elements (bitmap , textview etc..) directly for another thread defined inside that activity.

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. Handler can 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 a new Handler is created, it is bound to the thread/message queue of the thread that is creating it. To use a handler you have to subclass it and override handleMessage() to process messages.

There are two main uses for a Handler:

  • To schedule messages and runnables to be executed as some point in the future;
  • To enqueue an action to be performed on a different thread than your own.