Sobes.tech
Middle

How can you receive messages on the main thread using Handler and Looper?

sobes.tech AI

Answer from AI

  1. Create a Handler: Associate it with the Looper of the main thread.
  2. Send a Runnable or Message: Dispatch them via the Handler for execution on the associated thread (in this case - the main thread).
// On the main thread
val mainHandler = Handler(Looper.getMainLooper())

// Creating and sending a Runnable
mainHandler.post {
    // Code to run on the main thread
}

// Creating and sending a Message
val message = Message.obtain().apply {
    what = 1 // Arbitrary message identifier
    obj = "hello" // Additional data
}
mainHandler.sendMessage(message)
  • Looper.getMainLooper() gets the Looper associated with the main thread.
  • Handler(Looper.getMainLooper()) creates a Handler that will process messages sent to it on the main thread.
  • post(Runnable) queues the Runnable in the Looper's message queue for execution.
  • sendMessage(Message) sends a message to the Looper's message queue.

Alternative: Anonymous Handler class with handleMessage

You can override the handleMessage method in an anonymous Handler class to process messages.

// On the main thread or another thread where you need to create a Handler for the main thread
val myHandler = object : Handler(Looper.getMainLooper()) {
    override fun handleMessage(msg: Message) {
        // Code to run on the main thread upon receiving a message
        when (msg.what) {
            1 -> {
                val data = msg.obj as String
                // Process data
            }
        }
    }
}

// Sending a message from another thread
Thread {
    val message = Message.obtain().apply {
        what = 1
        obj = "world"
    }
    myHandler.sendMessage(message)
}.start()

In this case, when a message is received, the handleMessage method will be called on the main thread.