Enric
Enric

Reputation: 55

Android, How to keep a CountDownTimer running while other activity is Launched

Hello I have an Activity that shows a CountDown in a textView (using CountDownTimer), but when I Launch an other activity (config screen) or change screen orientation the countDownTimer is stopped and I want keep this timer running in background, I tried to make a thread with the CountDowntimer inside, but it doesn't work, anyone Knows a way to do that?

Thank You.

Upvotes: 3

Views: 2580

Answers (2)

KnightCavalry
KnightCavalry

Reputation: 387

You can override onPause method and stop the timer then save last value there. You also need to override onResume and start your timer with last value.

Upvotes: 1

Peter Knego
Peter Knego

Reputation: 80340

You don't have to make a background thread to have a timer running. Just remember the time when timer was started, then when you need to restart it just show the time base on this remembered time value.

So:

  1. When starting a timer by user, record the system time as a start time.
  2. Start the timer inside the AsyncTask and update the UI based on the recorded start time.
  3. When Activity goes away, just stop the asyncTask.
  4. When Activity becomes Active, restart the AsyncTask and proceed with 2.
  5. When user stops the timer, reset the start time and stop the asyncTask

Upvotes: 4

Related Questions