[Tutorial] Learn to create a Countdown Timer on Android

sylsau

Active member
Nov 8, 2011
35
0
0
Visit site
Hello,

I create that thread to present you a tutorial showing you how to create a a Countdown Timer on Android. The tutorial is also available on my website here : 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.

1/ 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 :

Code:
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.

2/ Manage your CountDown Timer

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

Code:
countDownTimer.start();

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

Code:
countDownTimer.cancel();

3/ Conclusion

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

4/ Extra

You can also enjoy this tutorial on Youtube :


Don't hesitate to give me your feedbacks and ideas for new tutorials.

Thanks.

Sylvain
 

Members online

Forum statistics

Threads
943,170
Messages
6,917,627
Members
3,158,860
Latest member
smokedog87