CountDownTimer cancel() not Working

2019-02-24 10:28发布

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();
        }

1条回答
干净又极端
2楼-- · 2019-02-24 11:15

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();
}
查看更多
登录 后发表回答