Sobes.tech
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:

  1. The thread that wants to use the Looper calls Looper.prepare() to create a Looper and MessageQueue.
  2. The thread calls Looper.loop() to start the message processing loop. This function blocks the thread until Looper.quit() is called.
  3. The Handler creates and sends messages to the MessageQueue associated with this Looper.
  4. 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
    }
}