How to Set Up a CountDownTimer

In this post, I’m going to show you how to set up a CountDownTimer properly. Let’s take a look at the following code:

In my MainActivity, I first initialized and overrode necessary methods before starting CountDownTimer. Its constructor takes two parameters, the first of which is how much milliseconds later CountDownTimer is going to end, and the second one is the time interval (in milliseconds) between CountDownTimer ticks. The method onTick() is called each time after an interval we set passes, and the other method onFinish() is called when the entire countdown process finishes. Both these methods run on UI thread, so you can safely implement your UI manipulations inside them.

Lastly, since we set up our CountDownTimer inside onCreate() of our Activity, we need to cancel it and set it to “null” inside onDestroy().

Leave a Reply

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