Junior — Middle
How can a message be acquired in the main thread using Handler and Looper?
sobes.tech AI
Answer from AI
In Android, the Looper class is primarily used to process messages in the main (UI) thread, creating a message processing loop, and the Handler class places messages into this Looper's queue.
To receive messages in the main thread:
- Call
Looper.getMainLooper()in the main thread, which returns the main thread's Looper. - Create a Handler associated with this Looper:
Handler handler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
// Handle message in the main thread
}
};
- Messages or Runnable objects can be sent to this Handler, and they will be processed in the main thread.
Thus, Handler and Looper provide a message queue and processing mechanism in the main thread, allowing safe UI updates from other threads.