embersofadyingfire embersofadyingfire - 3 months ago 18
Android Question

How to pause, and resume a TimerTask/ Timer

I have an animation in my Android app that flashes a TextView different colors. I've used a TimerTask, Timer, and Runnable method to implement this. What I need to do is stop the thread when a user leaves the app during this animation in onPause(), and resume the thread when the user returns to the app in onResume(). The following is the code I've implemented, but it's not working (the onPause(), and onResume() pieces), and I don't understand why. I've read a few other posts on similar matters, but they haven't helped me figure out what to do in my situation. I've read that TimerTasks are outdated, and I should probably use an ExecutorService method; it is unclear to me as how to implement this function.

...timerStep5 = new TimerTask() {

@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (b5) {
cashButton2SignalText.setBackgroundColor(Color.RED);
cashButton2SignalText.setTextColor(Color.WHITE);
b5=false;
} else {
cashButton2SignalText.setBackgroundColor(Color.WHITE);
cashButton2SignalText.setTextColor(Color.RED);
b5=true;
}
}
});
}
};

timer5.schedule(timerStep5,250,250);

}

public void onPause(){

super.onPause();

timerStep5.cancel();

}

public void onResume(){

super.onResume();

timerStep5.run();

}

Answer

After a TimerTask is canceled, it cannot run again, you have to create a new instance.

Read details here:

http://stackoverflow.com/a/2098678/727768

ScheduledThreadPoolExecutor is recommended for newer code, it handles the cases like exceptions and task taking longer time than the scheduled interval.

But for your task, TimerTask should be enough.