Android : Android TimerTask won't stop using "timer.cancel()", when onPause

on Tuesday, July 29, 2014


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);

}

0 comments:

Post a Comment