Middle
What is a Looper in Android?
sobes.tech AI
Answer from AI
Looper is an object designed for executing a task multiple times within a single thread. It creates an event loop that processes messages from a message queue (MessageQueue).
Main components:
- MessageQueue: A queue of tasks or messages.
- Looper: An object that retrieves messages from the MessageQueue and sends them to the appropriate Handler.
- Handler: An object associated with a specific Thread and MessageQueue. It is used to send messages to the MessageQueue and process them.
Working principle:
- The thread that wants to use the Looper calls
Looper.prepare()to create a Looper and MessageQueue. - The thread calls
Looper.loop()to start the message processing loop. This function blocks the thread untilLooper.quit()is called. - The Handler creates and sends messages to the MessageQueue associated with this Looper.
- The Looper retrieves messages from the MessageQueue in order and passes them back to the Handler for processing in the
handleMessage()method.
Applications:
- User interface (UI Thread) threads in Android use Looper to handle events like clicks and touches without blocking the UI.
- Background threads can use Looper to perform repetitive tasks or process messages sent from other threads.
// Example of creating and starting a Looper in a background thread
class WorkerThread extends Thread {
public Handler handler;
public void run() {
Looper.prepare(); // Create Looper and MessageQueue for this thread
handler = new Handler(Looper.myLooper()) { // Create Handler
@Override
public void handleMessage(Message msg) {
// Process message here
}
};
Looper.loop(); // Start the message processing loop
}
}