问题
I to restart a CountDownTimer. I read a lot of question here but no one of the answer helped me. When I use the following code
if(Const.counter != null){
Const.counter.cancel();
Const.counter = null;
}
Const.counter = new CustomTimerTask(Const.currentLevel.timeGoal * 1000,1000);
Const.counter.start();
I start a new counter but the old one also continues work. Please hekp me solve it.
回答1:
You can realize it by cancelling and restarting. The following example should work.
CountDownTimer mCountDownTimer = new CountDownTimer(500, 1000) {
@Override
public void onTick(long millisUntilFinished) {}
@Override
public void onFinish() {
isCounterRunning = false;
}
};
boolean isCounterRunning = false;
private void yourOperation() {
if( !isCounterRunning ){
isCounterRunning = true;
mCountDownTimer.start();
}
else{
mCountDownTimer.cancel(); // cancel
mCountDownTimer.start(); // then restart
}
}
回答2:
I did some different trick here. Hope this will help you.
if (myCountDownTimer != null) {
myCountDownTimer.cancel();
}
myCountDownTimer = new MyCountDownTimer(10000, 500);
myCountDownTimer.start();
回答3:
coutdown timer for quiz
if(countDownTimer!=null)
{
countDownTimer.cancel();
countDownTimer.start();
}
else {
countDownTimer = new CountDownTimer(30000, 1000) {
public void onTick(long l) {
mtimer.setText("remaining time" + l / 1000);//mtime is a textview
}
public void onFinish() {//here mnext is the button from which we can get next question.
mnext.performClick();//this is used to perform clik automatically
}
}.start();
来源:https://stackoverflow.com/questions/19997588/countdowntimer-in-android-how-to-restart-it