2

I am trying to stop a Timer or TimerTask, but the method doesn't destroy the task...

First the code how i set up the timertask:

 scanTask = new TimerTask() {
    public void run() {
            handler.post(new Runnable() {
                    public void run() {
                     load_unread();
                     Log.d("TIMER", "Timer set off");
                    }
           });
    }};

t=new Timer(); t.schedule(scanTask, 300, 10000);

and now I'm trying to "kill" this Task at onDestroy:

@Override
protected void onDestroy() {
    super.onDestroy();
    scanTask.cancel();
    t.cancel();
    t.purge();
    handler.removeCallbacksAndMessages(null);
    System.out.println("Chat destroyed");
}

but this doesn't work? Can you please help me finding a solution?

Thanks!

EDIT: I finally found the answer. Don't know why mine didn't work...

Here the code for everyone who has the same Problem. I think this is a better and more efficient solution anyway:

private Handler handler = new Handler(); runnable.run();

private Runnable runnable = new Runnable() 
{

    public void run() 
    {
         //
         // Do the stuff
         //

         handler.postDelayed(this, 1000);
    }
};

and to stop:

handler.removeCallbacks(runnable);

taken from here:

https://stackoverflow.com/a/11640073/1956197

Community
  • 1
  • 1
Matthew Fisher
  • 173
  • 1
  • 15

3 Answers3

2

After looking at your edit, the only thing I'd suggest is to use handler.post(runnable); instead of runnable.run(); This way you are always executing your runnable on a separate thread. Otherwise, your first execution will run on the main thread, then future executions run inside the handler on a separate thread.

    final Handler handler = new Handler();

    Runnable runnable = new Runnable() {

        public void run() {
            //
            // Do the stuff
            //

            handler.postDelayed(this, 1000);
        }
    };

    handler.post(runnable);
invertigo
  • 6,336
  • 5
  • 39
  • 64
0

Cancel the TimerTask before setting it to null.

scanTask.cancel();
invertigo
  • 6,336
  • 5
  • 39
  • 64
0

this example start the timer unitl destroyed

 private lateinit var timerTask: TimerTask

 timerTask = object : TimerTask() {
        override fun run() {
            Log.d("KTZ", "$minutes:$seconds");
            timeRecordingLiveData.postValue("$minutes:$seconds")
            seconds += 1;
            if (seconds == 60) {
                Log.d("KTZ", "$minutes:$seconds");
                timeRecordingLiveData.postValue("$minutes:$seconds")
                seconds = 0;
                minutes += 1;
            }
        }

    }

Cancel the timertask in onDestroy()

    timerTask.cancel()