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?

+3
java android countdowntimer


source to share


2 answers


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

.

+5


source to share


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

      



0


source to share







All Articles
Loading...
X
Show
Funny
Dev
Pics