CountDownTimer cancel() not Working

南笙酒味 提交于 2019-12-20 02:39:20

问题


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:


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


来源:https://stackoverflow.com/questions/27730115/countdowntimer-cancel-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!