Understanding Android Handler Class for UI Updates
Q: Can you explain the use of the Handler class in Android? Can you show an example of how to use it to update the UI thread?
- Android
- Mid level question
Explore all the latest Android interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create Android interview for FREE!
The Handler class in Android is used to send and
process messages between threads. It is often used in conjunction with the Looper
class to create a message queue that allows background threads to communicate
with the UI thread, which is responsible for updating the user interface.
Here's an example of how to use a Handler to update
the UI thread:
// Define a Handler that will run on the UI thread Handler handler = new Handler(Looper.getMainLooper()); // In the background thread, send a message to the Handler to update the UI new Thread(new Runnable() { public void run() { // Do some time-consuming operation // ... // Send a message to the Handler to update the UI handler.post(new Runnable() { public void run() { // Update the UI textView.setText("Updated text"); } }); } }).start();
In this example, we first define a Handler that will
run on the UI thread using Looper.getMainLooper(). We then create a new
background thread to perform a time-consuming operation. Once the operation is
complete, we use handler.post() to send a message to the Handler
that will update the UI. The message contains a Runnable that will be
executed on the UI thread, and in this Runnable, we update a TextView
with new text.
By using a Handler to update the UI thread, we can
ensure that the user interface is updated in a safe and efficient way, without
blocking the UI thread or causing any performance issues.


