Skip to main content

Introduction to Handler in Kotlin Android

Introduction to Handler in Kotlin Android

A Handler is a class provided by the Android framework that allows you to communicate between different threads in an Android application. It is commonly used to schedule tasks to be executed on a certain thread, or to queue messages or runnables to be processed later.

Step 1: Create a Handler object

To use the Handler class in your Kotlin Android application, you need to create an instance of it. You can do this by either creating a new instance directly or by using the Handler() constructor.

val handler = Handler()

Step 2: Post a Runnable to the Handler

One of the key functionalities of a Handler is its ability to post runnables to be executed on a specific thread. You can use the post() method of the Handler object to achieve this.

handler.post {
// Code to be executed on the thread associated with the Handler
}

For example, let's say you want to update the UI from a background thread. You can use a Handler to post a runnable that performs the UI update.

val handler = Handler()

Thread {
// Perform some background task

handler.post {
// Update the UI
}
}.start()

Step 3: Delayed Execution with Handler

The Handler class also provides a way to schedule a runnable to be executed after a certain delay. You can use the postDelayed() method to achieve this.

handler.postDelayed({
// Code to be executed after the delay
}, delayInMillis)

For example, if you want to show a toast message after a delay of 1 second, you can use the following code:

val handler = Handler()

handler.postDelayed({
Toast.makeText(context, "Delayed toast message", Toast.LENGTH_SHORT).show()
}, 1000)

Step 4: Remove Pending Runnables

Sometimes, you may need to remove any pending runnables from the Handler's message queue. You can use the removeCallbacks() method to achieve this.

handler.removeCallbacks(runnable)

For example, if you have scheduled a runnable to be executed after a delay but want to cancel it before it runs, you can use the following code:

val handler = Handler()

val runnable = Runnable {
// Code to be executed
}

handler.postDelayed(runnable, 1000)

// Cancel the scheduled runnable
handler.removeCallbacks(runnable)

Step 5: Communication between Threads

One of the main use cases of a Handler is to communicate between different threads. You can send messages from one thread to another using a Handler.

val handler = Handler()

Thread {
// Perform some background task

val message = Message.obtain()
message.what = MESSAGE_ID
message.obj = data

handler.sendMessage(message)
}.start()

In the receiving thread, you can override the handleMessage() method of a Handler to handle the incoming message.

val handler = object : Handler(Looper.getMainLooper()) {
override fun handleMessage(message: Message) {
when (message.what) {
MESSAGE_ID -> {
val data = message.obj as Data
// Process the data
}
}
}
}

Handler Examples