Skip to main content

How to use Handler.Callback interface in Kotlin Android for message handling.

How to use Handler.Callback interface in Kotlin Android for message handling..

Here is a step-by-step tutorial on how to use the Handler.Callback interface in Kotlin Android for message handling:

Step 1: Create a Handler object First, create an instance of the Handler class in your Kotlin Android activity or fragment. The Handler class allows you to send and process messages and runnable objects associated with a thread's message queue.

val handler = Handler()

Step 2: Implement the Handler.Callback interface Implement the Handler.Callback interface in your activity or fragment. This interface has a single method called handleMessage, which is invoked when a message is received by the handler.

class MyActivity : AppCompatActivity(), Handler.Callback {

override fun handleMessage(msg: Message): Boolean {
// Handle the message here
return true
}

// Rest of the activity code...
}

Step 3: Set the callback for the Handler Set the callback for the handler by passing the current class instance to the Handler constructor.

val handler = Handler(this)

Step 4: Send messages To send a message to the handler, create an instance of the Message class and send it using the handler's sendMessage method.

val message = Message.obtain()
message.what = 1 // Set an identifier for the message
handler.sendMessage(message)

Step 5: Handle messages Inside the handleMessage method, you can handle different messages based on their identifiers using a when statement or if-else conditions.

override fun handleMessage(msg: Message): Boolean {
when (msg.what) {
1 -> {
// Handle message with identifier 1
return true
}
2 -> {
// Handle message with identifier 2
return true
}
// Add more cases as needed
else -> return false
}
}

Step 6: Remove pending messages If you need to remove any pending messages from the message queue, you can use the removeMessages method.

handler.removeMessages(1) // Remove messages with identifier 1

Step 7: Send delayed messages To send a delayed message, you can use the sendMessageDelayed method instead of sendMessage.

val message = Message.obtain()
message.what = 1
handler.sendMessageDelayed(message, 1000) // Send message with a delay of 1000 milliseconds

Step 8: Clean up Remember to clean up the handler when your activity or fragment is destroyed to avoid memory leaks.

override fun onDestroy() {
super.onDestroy()
handler.removeCallbacksAndMessages(null) // Remove all callbacks and messages
}

That's it! You have now learned how to use the Handler.Callback interface in Kotlin Android for message handling.