Middle
What is a Looper in Android?
sobes.tech AI
Answer from AI
Looper is a class in Android used for working with message queues (MessageQueue) in threads. It links a thread with a message queue, allowing it to receive and process messages from that queue.
Working principle:
- Creating a Looper: In a thread that needs a message queue,
Looper.prepare()is called. - Starting the loop:
Looper.loop()is called. This call blocks the thread until theLooperis stopped. Inside theLooperloop, it continuously retrieves messages from theMessageQueueand sends them to the targetHandler. - Stopping the Looper: To end the
Looper,Looper.quit()orLooper.quitSafely()is called.
Handler is used to send messages to the MessageQueue of the Looper and process them in the thread associated with that Looper. Example usage:
// In the thread where the Looper should be
new Thread(() -> {
Looper.prepare(); // 1. Creates a Looper and MessageQueue for this thread.
Handler handler = new Handler(Looper.myLooper()) { // 2. Creates a Handler associated with this thread's Looper.
@Override
public void handleMessage(Message msg) {
// Process message in this thread
}
};
Looper.loop(); // 3. Starts the Looper loop to process messages.
}).start();
// In another thread, sending a message
handler.sendMessage(/* your message */);
Looper is essential for threads to handle asynchronous tasks and interactions between threads, especially when working with the UI thread (which by default has a Looper).