Skip to main content

How to send a delayed message to a Handler in Kotlin Android

How to send a delayed message to a Handler in Kotlin Android.

Here is a step-by-step tutorial on how to send a delayed message to a Handler in Kotlin Android:

  1. Create a new Android project in your preferred IDE.

  2. Open the MainActivity.kt file and import the necessary classes:

import android.os.Handler
import android.os.Message
  1. Declare a Handler variable at the top of your MainActivity class:
private lateinit var handler: Handler
  1. Initialize the Handler in the onCreate method of your activity:
handler = object : Handler() {
override fun handleMessage(msg: Message) {
// Handle the delayed message here
  1. Define a constant to represent the delay time in milliseconds:
private val DELAY_TIME: Long = 2000
  1. Create a method to send a delayed message to the Handler:
private fun sendMessageWithDelay() {
val message = Message.obtain(handler)
handler.sendMessageDelayed(message, DELAY_TIME)
  1. Call the sendMessageWithDelay method wherever you want to send a delayed message. For example, you can call it inside a button click listener:
button.setOnClickListener {
  1. To perform an action when the delayed message is handled, modify the handleMessage method in the Handler:
override fun handleMessage(msg: Message) {
// Perform the desired action
showToast("Delayed message received!")
  1. Add a helper method to display a toast message:
private fun showToast(message: String) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
  1. Run your application and click the button. After the specified delay, the delayed message will be handled, and you will see a toast message displaying "Delayed message received!".

That's it! You have successfully sent a delayed message to a Handler in Kotlin Android. You can use this technique to perform tasks after a certain delay, such as updating UI elements, running background tasks, or scheduling events.