Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CountDownTimer cancel() not Working

I am new to Android Development and trying to make little Game. CountDownTimer.cancel() is not working for me.

Any Idea?

Thank Your for your Answer!

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();
        }
like image 577
Jagath Banneheka Avatar asked Jan 09 '23 04:01

Jagath Banneheka


1 Answers

I have to do an assumption right here because the code doesn't show much! apparently you are using the countDownTimer inside your onCreate as an inner class so that will trigger the timer when startTimer == true and it would create the object no matter what! I guess it would be better to create a global instance of CountDownTimer.

And write your code in this way:

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();
}
like image 162
Ahmad Sanie Avatar answered Jan 16 '23 09:01

Ahmad Sanie