Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CountDownTimer in android - how to restart it

I have 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 started a new counter but the old one also continues work. Please help me solve it.

like image 577
GO VEGAN Avatar asked Nov 15 '13 09:11

GO VEGAN


People also ask

How do I pause resume and CountDownTimer in Android?

Click to start then click again to pause and to resume, click again the timer's text view.

How do you keep a CountDownTimer running even if the app is closed?

To keep the timer running while the app is closed, you need to use a service. Listen to the broadcast of the service in the activity. See this SO answer to learn whether registering the receiver in onCreate, onStart, or onResume is right for you.

How do I set a countdown clock on my Android?

we can set count down time after completion of time it will stop and get 0 values. onTick(long millisUntilFinished ) - In this method we have to pass countdown mill seconds after done countdown it will stop Ticking. onFinish() - After finish ticking, if you want to call any methods or callbacks we can do in onFinish().


2 Answers

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
    }

}
like image 111
Lazy Ninja Avatar answered Sep 28 '22 17:09

Lazy Ninja


I did some different trick here. Hope this will help you.

if (myCountDownTimer != null) {
            myCountDownTimer.cancel();
        }
        myCountDownTimer = new MyCountDownTimer(10000, 500);
        myCountDownTimer.start();
like image 43
WASEEM Avatar answered Sep 28 '22 18:09

WASEEM