Middle
How can you receive messages on the main thread using Handler and Looper?
sobes.tech AI
Answer from AI
- Create a
Handler: Associate it with theLooperof the main thread. - Send a
RunnableorMessage: Dispatch them via theHandlerfor 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 theLooperassociated with the main thread.Handler(Looper.getMainLooper())creates aHandlerthat will process messages sent to it on the main thread.post(Runnable)queues theRunnablein theLooper's message queue for execution.sendMessage(Message)sends a message to theLooper'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.