Junior
What is a Handler in Android?
sobes.tech AI
Answer from AI
Handler in Android is a mechanism for sending and processing messages and Runnable objects associated with a message queue (MessageQueue) of a specific thread (Looper).
A Handler is bound to the thread in which it was created (or explicitly specified during creation), which has a Looper and MessageQueue. It allows scheduling code execution in that thread.
Main functions of Handler:
- Sending: Placing messages (Message) or Runnables at the end of the current thread's message queue or at another position.
- Processing: Receiving messages from the queue and processing them (by calling
handleMessage()callback or executing Runnable).
Typical usage scenarios:
- Moving execution from a background thread to the main (UI) thread: Updating UI elements that can only be changed from the main thread.
- Delayed code execution: Deferred execution of a task after a certain time.
- Scheduling recurring tasks: Performing a task at regular intervals.
Main components related to Handler:
- Handler: The object that sends and processes messages.
- Message: An object containing data for transfer between threads.
- Runnable: Interface for executing tasks in another thread.
- Looper: Runs an infinite loop that retrieves messages from the queue.
- MessageQueue: Queue of messages processed by the Looper.
Example of using Handler to execute code in the UI thread from a background thread:
// In a background thread
new Thread(new Runnable() {
@Override
public void run() {
// Perform a long operation
final String result = performLongOperation();
// Pass the result to the UI thread using Handler
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
// Update UI element in the UI thread
textView.setText(result);
}
});
}
}).start();