Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dispose CountDownTimer

I have main class called "MainActivity" and I'm lanuching it few times in my App.

private static CountDownTimer timer;
private static final long startTime = 15 * 1000;
private static final long interval = 1 * 1000;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    timer = new StageCountDownTimer(startTime, interval);

}

private class StageCountDownTimer extends CountDownTimer {
    public StageCountDownTimer(long startTime, long interval) {
        super(startTime, interval);
    }

    @Override
    public void onFinish() {
        //STARTTING NEW ACTIVITY 
    }

    @Override
    public void onTick(long millisUntilFinished) {
    }
}

Sometimes user need to close this activity before count down ends, and return to the this activity again. And then new count down is launching but the old one execute the code in onFinish() when previous count down ends. Everything works great when I start this code once. How to cancel/dispose/destroy this timer after exiting from activity? I tried timer.cancel() and nothing happen.

EDIT

I think I solved my problem by setting CountDownTimer timer as a public and in other Activity i'm just using MainActivity.timer.cancel()

like image 732
Jakub Pomykała Avatar asked Sep 15 '13 18:09

Jakub Pomykała


2 Answers

You can use:

if (isFinishing()) {
    CountDownTimer.cancel();
}

so if the acitvity is finishing, the countdowntimer gets canceled. and next time you open the acitvity, new countdowntimer will be up.

like image 137
Ahmed Ekri Avatar answered Nov 09 '22 10:11

Ahmed Ekri


In addition to timer.cancel() (which should work) you can do in your timer's onFinish():

@Override
    public void onFinish() {
        if(!MainActivity.this.isFinishing()) {
             // Start new activity...
        }
    }
like image 28
Alexander Kulyakhtin Avatar answered Nov 09 '22 10:11

Alexander Kulyakhtin