Reputation: 3305
I was reading a number of posts here about stoping a Timer using the cancel(); method, but no matter how I try, the timer keeps running in the background after onPause() occurs.
(Note that I am executing an AsyncTask inside the timer, I know that it was meant to be run only once, but I am afraid that if I run the AsyncTask on the main thread it will hang up my main activity.)
So why the timer won't stop onPause() ?
} //end on create
@Override
protected void onPause() {
super.onPause();
this.timer.cancel();
this.timer.purge();
}
@Override
protected void onResume() {
super.onResume();
callAsynchronousTask();
}
public void callAsynchronousTask() {
final Handler handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
MyTask task = new MyTask();
task.execute("Param 1", "Param 2", "Param 3");
} catch (Exception e) {
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 2000);
}
Upvotes: 1
Views: 2083
Reputation: 8023
When you cancel your timer, the task
has already started executing. So, even if the timer gets cancelled, the AsyncTask executes in the background.
There is no ideal way to handle cancelling of an AsyncTask. You might want to check this question : Android - Cancel AsyncTask Forcefully
Upvotes: 1