How can I prevent the CountDownTimer function from being used in the background?
I am making an Android app that has a limit on the number of points you can get. But if you close the app, the timer keeps moving. How to pause CountDownTimer
when an app is suspended?
You can reverse it in onPause()
with something like
@Override
public void onPause()
{
super.onPause();
timer.cancel(); // timer is a reference to my inner CountDownTimer class
timer = null;
}
And use a variable millisUntilFinished
to store in SharedPreference
or some other constant variable. Then use that variable again to start the timer atonResume()
Common prefs
This answer might be helpful if you need to pass a value to another Activity
.
int totaltime=1000;
mTimer=new CountDownTimer(totaltime, 1000) {
public void onTick(long millisUntilFinished) {
saveElapsedTime();
}
public void onFinish() {
}
}.start();
void onPaus(){
mTimer.cancel();
}
onResume(){
int totaltime=1000;
mTimer=new CountDownTimer(totaltime-elapsedTime, 1000) {
public void onTick(long millisUntilFinished) {
saveElapsedTime();
}
public void onFinish() {
}
}.start();