Skip to main content

How to remove pending messages from a Handler in Kotlin Android

How to remove pending messages from a Handler in Kotlin Android.

Here's a detailed step-by-step tutorial on how to remove pending messages from a Handler in Kotlin for Android.

Step 1: Create a Handler object

First, you need to create a Handler object that will be used to handle messages and execute code on a specified thread. You can create a Handler object by calling its constructor and passing in the looper of the thread you want to run the code on.

val mHandler = Handler(Looper.getMainLooper())

In this example, we're creating a Handler object that runs on the main (UI) thread.

Step 2: Post messages to the Handler

Next, you can post messages to the Handler using the post() method. The post() method takes a Runnable object or a lambda expression that contains the code you want to execute. {
// Code to be executed

You can post multiple messages to the Handler by calling post() multiple times.

Step 3: Remove pending messages

To remove pending messages from the Handler, you can use the removeCallbacks() method. This method removes all Runnable objects that haven't been executed yet.


In this example, we're passing null as the parameter to remove all pending messages. If you want to remove specific messages, you can pass a Runnable object or a Message object to removeCallbacks().

val myRunnable = Runnable {
// Code to be executed


Step 4: Remove specific messages with a token

If you want to remove specific messages from the Handler that were posted with a token, you can use the removeCallbacksAndMessages() method and pass the token as the parameter. This method removes all Runnable objects and Message objects that have the specified token.

val myToken = Any() // Create a unique token object

// Code to be executed
}, 1000, myToken)


In this example, we're posting a delayed message with a token and then removing all messages with that token.

Step 5: Clean up

Remember to clean up your Handler when it's no longer needed to prevent memory leaks. You can do this by calling the removeCallbacksAndMessages() method with null as the parameter before releasing the Handler.



In this tutorial, you've learned how to create a Handler object, post messages to it, and remove pending messages. You've also seen how to remove specific messages using tokens. By following these steps, you can effectively manage and remove pending messages from a Handler in your Kotlin Android application.