Search code examples
androidtimercountdowncountdowntimer

Android Countdown timer with double speed


I would like to create a countdown timer that starts at 10 but only takes 5 seconds to count down to 0.

I have this code below from Google Source Code that counts down from 10:

new CountDownTimer(10000, 1000) {
    public void onTick(long millisUntilFinished) {
        timerText.setText("seconds remaining: " + millisUntilFinished / 1000);
    }

    public void onFinish() {
        timerText.setText("done!");
    }
}.start();

Solution

  • You should actually try doing it yourself first, but:

    new CountDownTimer(5000, 500) {
    
        public void onTick(long millisUntilFinished) {
            timerText.setText("Half-seconds remaining: " + millisUntilFinished / 500);
        }
    
        public void onFinish() {
            timerText.setText("done!");
        }
    }.start();
    

    The CountDownTimer has two parameters in its constructor, one for the length of the timer as a whole (called millisInFuture, the first parameter), and one for how often the onTick function is called (which is countDownInterval). Both of these parameters are of the long variable type.

    Please see CountDownTimer in the Android API.