Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timer Not Stopping In Android

Tags:

android

THE PROBLEM I am having problems stopping the Timer whilst developing in android.

The timer is already null when it comes to stopping it.

I then move the timer initialisation to outside of a method just like the TimerTask which solves the null problem but still doesn't cancel when timer.cancel(); is called upon it.

The code below is an example of the timer already being null when it comes to stopping the recording.

TimerTask

My TimerTask is initialized inside the class but outside of a method and the codes below...

private TimerTask task = new TimerTask() {
    @Override
    public void run() {
      Log.e("TRACK_RECORDING_SERVICE","Timer Running");
    }
  };

Timer & Timer Start

I then have a startRecroding method which is called when I want to start the timer...

public void startRecording(){
     timer = new Timer("Message Timer");
     timer.scheduleAtFixedRate(this.task, 0, 1000);
 }

Timer Stop

I then call the below method when I want to stop the timer...

public void stopRecording() {
     if (timer != null) {
         timer.cancel();
         timer = null;
     } else {
         Log.e("TRACK_RECORDING_SERVICE","Timer already null.");
     }
 }

Any help would be much appreciated.

like image 221
StuStirling Avatar asked Jul 16 '12 10:07

StuStirling


2 Answers

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;
like image 155
Lucifer Avatar answered Oct 26 '22 01:10

Lucifer


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
    }
}
like image 24
Marlon Avatar answered Oct 26 '22 01:10

Marlon