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.