Implement a simple timer using CountDownTimer in Android using Kotlin or Java

In this post, I will be covering how to Implement a simple timer using CountDownTimer in Android using Kotlin or Java.

Implement a simple timer using CountDownTimer in Android using Kotlin or Java

Android provides a utility class called CountDownTimer that you use to implement the timer.

Schedule a countdown until a time in the future, with regular notifications on intervals that are set.

Implementing CountDownTimer in Kotlin Android

Add a private variable called timer which is of type CountDownTimer

private val timer: CountDownTimer

Inside the init block, initialize and start the timer. Pass in the total time for future and interval to trigger the timer.

timer = object : CountDownTimer(60000, 1000) {
   override fun onTick(millisUntilFinished: Long) {       
   }
   override fun onFinish() {       
   }
}
timer.start()

Creates a timer with 60 seconds future with an interval of 1 second. Note that the time must be specified in milliseconds.

Implement the onTick() callback method, which is called on every interval or on every tick.

The onFinish() callback method is called when the timer is finished. The API reference for Kotlin is available at Android Reference. Java reference is available here.

Related Posts

Conclusion

In this post, I showed you how to implement a simple timer using CountDownTimer in Android using Kotlin or Java. If you have any questions or just want to chat with me, feel free to leave a comment below.

Leave a Reply

Your email address will not be published. Required fields are marked *