CountDownTimer cancel () not working

I am new to android development and am trying to make a small game. CountDownTimer.cancel()

doesn't work for me.

Any idea?

Thanks for your reply!

CountDownTimer cdt = new CountDownTimer(120000, 1000) {

            public void onTick(long millisUntilFinished) {
                maxTime = (int) (millisUntilFinished / 1000);
                timer.setText(String.valueOf(maxTime));
            }

            public void onFinish() {

            }
        };

        if (startTimer == true) {
            cdt.start();
        } else {
            cdt.cancel();
        }

      

+3


source to share


1 answer


I have to make a guess right here because the code doesn't show much! apparently you are using countDownTimer

inside yours onCreate

as an inner class to start the timer when startTimer == true

and it would create an object no matter what! I think it would be better to create a global instance countDownTimer

.

And write your code like this:



if(startTimer == true) {
    cdt = new CountDownTimer(120000, 1000) {
        public void onTick(long millisUntilFinished) {
            maxTime = (int) (millisUntilFinished / 1000);
            timer.setText(String.valueOf(maxTime));
        }

        public void onFinish() {

        }
    }.start(); //start the countdowntimer
}
else{
    cdt.cancel();
}

      

+7


source







All Articles