Java Archives - Learn Smart Coding https://blogs.learnsmartcoding.com/tag/java/ Everyone can code! Tue, 20 Oct 2020 02:28:57 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.1 209870635 Implement a simple timer using CountDownTimer in Android using Kotlin or Java https://blogs.learnsmartcoding.com/2020/10/20/implement-a-simple-timer-using-countdowntimer-in-android-using-kotlin-or-java/ https://blogs.learnsmartcoding.com/2020/10/20/implement-a-simple-timer-using-countdowntimer-in-android-using-kotlin-or-java/#respond Tue, 20 Oct 2020 02:28:57 +0000 https://karthiktechblog.com/?p=751 In this post, I will be covering how to 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 […]

The post Implement a simple timer using CountDownTimer in Android using Kotlin or Java appeared first on Learn Smart Coding.

]]>
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.

The post Implement a simple timer using CountDownTimer in Android using Kotlin or Java appeared first on Learn Smart Coding.

]]>
https://blogs.learnsmartcoding.com/2020/10/20/implement-a-simple-timer-using-countdowntimer-in-android-using-kotlin-or-java/feed/ 0 751