4

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();
        }
M-Wajeeh
  • 17,204
  • 10
  • 66
  • 103

2 Answers2

10

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();
}
Ahmad Sanie
  • 3,678
  • 2
  • 21
  • 56
  • Thank god, you are the best... I was just about to give up on this ..... – jayz Jun 18 '16 at 11:28
  • I was calling startTimer method from both onCreate and onResume method. While when I call ctd.cancel(), it stops my one ctd object and other still running. Finally work when I remove startTimer method call from onCreate method. – tejraj Jan 30 '20 at 13:39
0
        Boolean Myboolean = true;
        CountDownTimer MyCountDownTimer = new CountDownTimer(10000, 1000)
        {
            @Override
            public void onFinish()
            {
            }

            @Override
            public void onTick(long millisUntilFinished)
            {
                Log.i("onTick" , String.valueOf((millisUntilFinished / 1000) % 60));
                if(!Myboolean ) { cancel(); }
            }

        }.start();

i had this issue , the CountDownTimer will not cancle with (MyCountDownTimer.cancel();) , the best way is to use Boolean , set the Boolean to false to cancel the CountDownTimer. in any place you want (Myboolean =false;)