Java – countdowntimer cancel() does not work
•
Java
I am new to Android development and try to make small games
Any ideas?
Thank you 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(); }
Solution
I have to make a hypothesis here, because the code doesn't show too much! Obviously, you use countdowntimer as the internal class in oncreate, so the timer will be triggered when starttimer = = true, and the object will be created anyway! I think it's best to create a global instance of countdowntimer
And write 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(); }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码