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?
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With