How does Handler work internally in Android SDK?

In Android, a Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. It is primarily used to manage and control threads and perform operations on the main UI thread. The Handler class enables you to communicate with the UI thread from a background thread, allowing for seamless updates and interactions with the user interface.

Internally, when a Handler is created, it is tied to the Looper of the thread in which it is created. The Looper continuously processes messages in the MessageQueue, allowing the Handler to handle messages and runnables sequentially. Each message processed by the Handler can trigger specific actions, which is crucial for maintaining UI responsiveness.

One of the common use cases for Handlers is to post delayed actions or to handle background tasks without blocking the main thread. Handlers can communicate with the MessageQueue using methods like sendMessage() and post().

Example:

// Creating a Handler associated with the main UI thread Handler handler = new Handler(Looper.getMainLooper()); // Posting a Runnable to be executed after a delay handler.postDelayed(new Runnable() { @Override public void run() { // Code to be executed after the delay Toast.makeText(context, "Hello, Handler!", Toast.LENGTH_SHORT).show(); } }, 2000); // Delay of 2000 milliseconds (2 seconds)

Android Handler MessageQueue Looper UI thread background tasks post delayed actions