Android Kotlin: How to do a task after a delay

Introduction

This code demonstrates two ways to perform a task after a delay in an Android application written in Kotlin. It utilizes the Handler class, a core Android component for managing tasks on different threads. The code showcases both automatic delay on app launch and a user-triggered delay with a button click.

Breakdown

The code consists of two main parts: the MainActivity class written in Kotlin and the activity_main.xml layout file.

  • MainActivity.kt:
    • This class defines the behavior of the main activity screen.
    • It initializes two member variables, button and textView, to reference the button and text view widgets defined in the layout file.
    • In the onCreate method:
      • It creates a Handler object linked to the main application thread (Looper.getMainLooper()) and uses it to post a delayed task. This task changes the text view's text to "Text changed after 5 seconds delay" after a 5-second delay (5000 milliseconds).
      • It initializes another instance of Handler.
      • It sets an on-click listener for the button. When the button is clicked:
        • A Runnable interface implementation is defined. This defines the task to be executed after the delay. In this case, it sets the text view's text color to red.
        • This Runnable is then posted to the Handler with a 4-second delay (4000 milliseconds).
  • activity_main.xml:
    • This file defines the layout of the main activity screen using ConstraintLayout.
    • It contains two elements:
      • A button with the text "Do Task After Delay".
      • A text view displaying initial text "TextView".

Summary

This code effectively demonstrates how to use Handler with postDelayed to schedule tasks with specific delays in an Android application. It showcases automatic delay on launch and user-triggered delay on button press, making the text view content and color change after designated time intervals. This approach is a fundamental way to introduce delayed actions in Android development using Kotlin.


MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.widget.Button
import android.widget.TextView


class MainActivity : Activity() {
    private lateinit var button:Button
    private lateinit var textView:TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // get the widgets reference from XML layout
        button = findViewById(R.id.button)
        textView = findViewById(R.id.textView)

        // start a 5 seconds delayed task using handler
        Handler(Looper.getMainLooper()).postDelayed({
            textView.text = "Text changed after 5 seconds delay."
        },5000)


        // initialize an instance of handler
        val handler = Handler(Looper.getMainLooper())

        // delayed task on button click
        button.setOnClickListener {
            val runnable = Runnable { // do some task on delay
                // set the text view  text color to red
                textView.setTextColor(Color.RED)
            }

            // schedule a 4 seconds delayed task
            handler.postDelayed(runnable, 4000)
        }
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="#DCDCDC"
    android:padding="32dp">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Do Task After Delay"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="16dp"
        android:fontFamily="sans-serif-condensed"
        android:gravity="center"
        android:text="TextView"
        android:textColor="#191970"
        android:textSize="33sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:text="TextView" />

</androidx.constraintlayout.widget.ConstraintLayout>
android kotlin - Do a task after a delay android kotlin - Do a task after a delay 2
More android kotlin tutorials