Learn to create a Countdown Timer on Android

Sometimes, when you make Android applications, you need to create a countdown. It can be useful in a board game for example if the player have a defined time to play. A lot of solutions exist to create a countdown in Java. Some are more complex than other. On Android, the SDK offers to developers an easy way to create a countdown timer : a dedicated class named CountDownTimer.

Note that you can also discover this tutorial in video on YouTube :

Create the CountDown Timer

Here, we consider a countdown of 60 seconds. So, we need to use the following code to create the CountDownTimer instance :

CountDownTimer countDownTimer = new CountDownTimer(60 * 1000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("Seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("Done !");
}
};

The second parameter lets you to define at which interval you must be notified during the countdown. You can update your User Interface in that method.

Manage your CountDown Timer

Once you have created your CountDownTimer object, you have to manage it. First, you can start it :

countDownTimer.start();

If you want to cancel your countdown timer before its end, you have just to call its cancel() method :

countDownTimer.cancel();

Conclusion

Powerful and easy to use, the CountDownTimer class is the ideal solution to create countdown timer on Android.

Written by

Entrepreneur / Developer / Blogger / Author. In Bitcoin We Trust: https://www.inbitcoinwetrust.net

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store