Saturday, August 15, 2020

android kotlin - Repeat a task periodically

MainActivity.kt

package com.example.jetpack

import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import kotlin.random.Random


class MainActivity : AppCompatActivity() {

    private lateinit var handler: Handler
    private lateinit var runnable: Runnable
    private var interval: Long = 1000L
    private val maxRepeat: Int = 5
    private var counter = 0

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

        // 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(
            255,
            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"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#EDEAE0"
    tools:context=".MainActivity">

    <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"
        android:backgroundTint="#100C08"
        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>