Sobes.tech
Junior — Middle

How to implement message exchange between threads using Handler and Looper?

sobes.tech AI

Answer from AI

In Android, a common way to communicate between threads is by using a combination of Handler and Looper.

  • Looper creates a message processing loop in a thread.
  • Handler allows sending and processing messages within this loop.

Example:

// Create a Looper and Handler in a worker thread
HandlerThread handlerThread = new HandlerThread("MyHandlerThread");
handlerThread.start();
Handler backgroundHandler = new Handler(handlerThread.getLooper()) {
    @Override
    public void handleMessage(Message msg) {
        // Process message in background thread
        Log.d("Handler", "Message received: " + msg.what);
    }
};

// Send a message from the main thread
backgroundHandler.sendEmptyMessage(1);

Thus, the main thread can send messages to the background thread via Handler, and Looper provides the message processing loop.