CountDownTimer in android - how to restart it

GO VEGAN picture GO VEGAN · Nov 15, 2013 · Viewed 21.7k times · Source

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.

Answer

Lazy Ninja picture Lazy Ninja · May 22, 2014

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
    }

}