Android Kotlin: How to repeat a task periodically

Repeating Tasks Periodically in Android with Kotlin

This code demonstrates how to schedule a task to run repeatedly in an Android application written in Kotlin. It utilizes the Handler class to manage a background thread and post delayed messages.

Code Breakdown

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

  • MainActivity.kt:
    • This class defines the activity that handles user interaction and UI updates.
    • It initializes a Handler object on the main thread using Looper.getMainLooper().
    • A button click triggers the scheduling of a task using handler.postDelayed(runnable, interval). This creates a Runnable object containing the actual task logic and schedules it to run after a specific delay (interval).
    • The doTask function is called by the Runnable and performs the following actions:
      • Increments a counter to track the number of repetitions.
      • Updates the text view with the current counter and a random background color.
      • Checks if the counter reaches the maximum repetition (maxRepeat).
        • If so, it removes the task from the queue using handler.removeCallbacks(runnable) and updates the text view with a completion message. The counter is reset for potential future use.
        • Otherwise, it reschedules the task with the same delay (handler.postDelayed(runnable, interval)) for the next iteration.
  • activity_main.xml:
    • This layout file defines the user interface elements for the activity.
    • It includes a button to initiate the task and a text view to display the results.

Summary

This code provides a simple example of scheduling a task to run periodically in Android using the Handler class. It demonstrates how to manage the repetition count and update the UI accordingly. This approach is suitable for lightweight tasks that don't require long execution times. For more complex scenarios, consider using alternative solutions like WorkManager or Coroutines with appropriate cancellation mechanisms.


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
import kotlin.random.Random


class MainActivity : Activity() {
    private lateinit var handler: Handler
    private lateinit var runnable: Runnable
    private var interval: Long = 1000L
    private val maxRepeat: Int = 5
    private var counter = 0

    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)

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

        // repeated task on button click
        button.setOnClickListener {
            runnable = Runnable { // do some task on delay
                // do the task after delay specified time
                doTask(handler)
            }

            // schedule the task to do after an interval
            handler.postDelayed(runnable, interval)
        }
    }


    private fun doTask(handler: Handler){
        counter += 1
        textView.text = "Task repeated $counter times."
        textView.setBackgroundColor(randomColor)

        // do a task maxRepeat times periodically
        if (counter == maxRepeat){
            // finish task after maxRepeat times done
            handler.removeCallbacks(runnable)
            textView.append("\nTask end.")
            counter = 0
        }else{
            // schedule the task to do again after an interval
            handler.postDelayed(runnable,interval)
        }
    }
}


// generate random color
val randomColor :Int
    get() {
        return Color.argb(
            175,
            Random.nextInt(150,255),
            Random.nextInt(150,255),
            Random.nextInt(150,255)
        )
    }
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="16dp"
        android:layout_marginTop="16dp"
        android:text="Do Task Periodically"
        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:fontFamily="sans-serif-condensed"
        android:gravity="center"
        android:text="Repeated Task"
        android:padding="32dp"
        android:textColor="#0014A8"
        android:textSize="35sp"
        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 - Repeat a task periodically android kotlin - Repeat a task periodically 2
More android kotlin tutorials