1

I am trying to show a CountDownTimer to user which start decreasing immediately a user press the 'START' button, but if I'm closing the activity and reopening it, the CountDownTimer is getting reset and getting start again.

I used this link to learn how to set a CountDownTimer.

Here's how I coded it:

new CountDownTimer(ms, 1000) {

            public void onTick(long millisUntilFinished) {
                String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
                        TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) % TimeUnit.HOURS.toMinutes(1),
                        TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) % TimeUnit.MINUTES.toSeconds(1));
                holder.availableFor.setText(hms);
            }

            public void onFinish() {
                holder.linearLayout.setVisibility(View.GONE);
                holder.firebaseDatabase.child(itemID).setValue(null);
                holder.geoFireReference.child(itemID).setValue(null);
            }
        }.start();

Please let me know how to keep the Timer going even if user closes the app.

Community
  • 1
  • 1
Hammad Nasir
  • 2,889
  • 7
  • 52
  • 133

3 Answers3

1

As I understand you're creating this timer in onClick method. Try to create some global variable

CountDownTimer timer

After that create it in onclick, as you do.

and in onpause:

if (timer != null) {
timer.cancel

}

Pein
  • 1,059
  • 3
  • 10
  • 31
1

You have to use service class here is the link which may be help you.

Community
  • 1
  • 1
shahid17june
  • 1,441
  • 1
  • 10
  • 15
0

You need to store the timer data in some global scope so the timer once set not get altered with activity life cycle.

best practice suggest, use service like answered by @shahid17june

also if you don't want to use that, or setup variable to store counttimerdata in application class (global data), and update it appropriately.