Sobes.tech
Junior

What is a Looper in Android?

sobes.tech AI

Answer from AI

Looper is a class in Android used to manage a thread, making it "loop" (cyclic). It prepares a thread to process messages from a message queue (MessageQueue) until explicitly terminated.

Main components of Looper:

  • MessageQueue: Queue storing messages (Message) and runnables (Runnable) for execution in the Looper thread. It is thread-safe.
  • Looper: Binds a thread to a MessageQueue and cyclically retrieves messages for processing.
  • Handler: An object that posts messages and runnables to the MessageQueue of a Looper and processes them upon retrieval. It is bound to a specific Looper.

How Looper works:

  1. Preparation: Call Looper.prepare() in the thread. It creates a new Looper instance and associates it with the current thread. It also creates a MessageQueue for this Looper.
  2. Start loop: Call Looper.loop(). This enters an infinite loop (until Looper is quit). It constantly checks MessageQueue for new messages.
  3. Message processing: When a message is found, Looper retrieves it and sends it to the Handler that posted it. The Handler executes the corresponding task (handleMessage() or run() for Runnable).
  4. Termination: To exit the loop and terminate the Looper, call Looper.quit() or Looper.quitSafely().

Typical use cases:

  • Creating background threads that perform asynchronous tasks and receive messages from the UI thread or other threads.
  • Using in services (e.g., IntentService uses an internal Looper).
  • Working with HandlerThread (a special thread class that creates its own Looper and MessageQueue).

Example of creating a thread with Looper and Handler:

// Create and start thread
HandlerThread handlerThread = new HandlerThread("MyWorkerThread");
handlerThread.start();

// Get Looper from thread
Looper looper = handlerThread.getLooper();

// Create Handler bound to Looper
Handler handler = new Handler(looper);

// Send task to thread
handler.post(new Runnable() {
    @Override
    public void run() {
        // Code executed in worker thread
        System.out.println("Thread created with HandlerThread")
    }
});

This pattern is useful for offloading work from the main thread and managing message-driven communication.