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

  1. Creating a Looper: In a thread that needs a message queue, Looper.prepare() is called.
  2. Starting the loop: Looper.loop() is called. This call blocks the thread until the Looper is stopped. Inside the Looper loop, it continuously retrieves messages from the MessageQueue and sends them to the target Handler.
  3. Stopping the Looper: To end the Looper, Looper.quit() or Looper.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).

What is a Looper in Android? — Android - sobes.tech