Timer Not Stopping In Android

Ok so the problem was in the instantiation not the actual stopping of the timer.

Everytime I called:

timer = Timer()
timer!!.scheduleAtFixedRate(object : TimerTask() {
    override fun run() {
       //something  
    }
}, delay, period)

It created another instance so the old instance was still running somewhere with no way to stop it.

So I just made sure to instantiate it when the timer is null so that no previous instance is getting pushed around and still running on the background.

if(timer == null) {
    timer = Timer()
    timer!!.scheduleAtFixedRate(object : TimerTask() {
        override fun run() {
            // something
        }
    }, delay, period)
}

Then just cancel it and set it to null.

fun stopTimer() {
    if (timer != null) {
        timer!!.cancel()
        timer!!.purge()
        timer = null
    }
}

timer = new Timer("Message Timer"); 

Here your object timer is not a static so timer.cancel(); will cancel another instance of the Timer class. I suggest you to create a static instance variable of Timer Class on the top of the class, like below,

private static Timer timer;

in the run() method, check if timer is null then

private TimerTask task = new TimerTask() {
@Override
public void run() {
if (timer == null)
	cancel();
...
}

cancel the operation.


if(waitTimer != null) {
   waitTimer.cancel();
   waitTimer.purge()
   waitTimer = null;
}

Tags:

Android