Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android relaunching Timers after they are canceled

I have a timer in my application that launches an AsyncTask every 15 secs.

Timer timer = new Timer();

public void AsynchTaskTimer() {
    final Handler handler = new Handler();

    TimerTask timertask = new TimerTask() {
        @Override
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    try {
                        new updateGPSTask().execute();
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                    }
                }
            });
        }
    };
    timer.schedule(timertask, 0, 15000); // execute in every 15sec
}

This is launched from the onCreate() method.

When I call another activity I need to cancel this timer, which I did using timer.cancel() on my onPause() method in my Main Activity.

Now when I return to the Main Activity I need to restart the timer. I tried relaunching the AsynchTaskTimer() in the onRestart() method, but I get a java.lang.IllegalStateException: Timer was canceled.

How do I restart my timer?

like image 733
pteixeira Avatar asked Mar 28 '13 11:03

pteixeira


2 Answers

Try using :

public void AsynchTaskTimer() {
    final Handler handler = new Handler();

    TimerTask timertask = new TimerTask() {
        @Override
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    try {
                        new updateGPSTask().execute();
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                    }
                }
            });
        }
    };
    timer = new Timer(); //This is new
    timer.schedule(timertask, 0, 15000); // execute in every 15sec
    }

By using this you can again allocate the memory to Timer and start it AFAIK.

like image 157
Sanober Malik Avatar answered Sep 27 '22 22:09

Sanober Malik


So what says docs about cancel() method:

Note that calling this method from within the run method of a repeating timer task absolutely guarantees that the timer task will not run again.

It means that if you once cancel() Timer you can't to run it again. You need to create new instance of Timer, for example in onResume() method if you want to run it again.

@Override
public void onResume() {
   super.onResume();
   // intialise new instance of Timer
}
like image 43
Simon Dorociak Avatar answered Sep 27 '22 22:09

Simon Dorociak