How to dispose CountDownTimer
Asked Answered
J

3

5

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()

Josie answered 15/9, 2013 at 18:11 Comment(1)
static CountDownTimer creates a memory leak here.Immateriality
P
6

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.

Poling answered 15/9, 2013 at 18:14 Comment(1)
If you are using a fragment, just add cancel() to onDetach() lifecycle methodCounterrevolution
A
2

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...
        }
    }
Arredondo answered 15/9, 2013 at 18:15 Comment(0)
J
0

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

Josie answered 15/9, 2013 at 18:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.