Android relaunching Timers after they are canceled

android, android-asynctask, timer

Solution

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.

Problem

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?

Original source