0

How i should implement a countdown timer if i need the following usage:

  1. User starts activity A;
  2. In activity A he starts the timer;
  3. User leaves activity A, timer runs in background;
  4. User comes back to activity A;
  5. User see current (updated) values of the timer;

I tried to use a Countdown Timer but it fails at step 5 - after returning to ativity A i cant see values in TextView (in LogCat i do) and system starts another timer (this way, every activity re-open starts one more timer). Should I use service instead or ... show me the way, please.

P. Savrov
  • 1,064
  • 4
  • 17
  • 29
  • You should use a service for the timer (background), and recover its information when you are returning to activity A. May this will help http://stackoverflow.com/questions/16510462/how-to-keep-activity-running-in-background – Kenzo_Gilead Aug 23 '16 at 10:57
  • 1
    You should save time stamp in sharedprefs in onPause and in onResume you should get current time and saved time stamp, difference of these timestamps will give you elapsed time. Now start a new timer with remaining time. – rajesh Aug 23 '16 at 11:06
  • Make your textview as static – Jinesh Francis Aug 23 '16 at 11:50
  • @rajesh, bro, i did it in your way. it works. if u post it like an answer i'll mark it. – P. Savrov Aug 23 '16 at 15:17

1 Answers1

0

You can't be sure that after you leave your activity it will be still alive. System could kill it at any time.

The solutions for this use case could be:

  1. Start timer in foreground Service. Such types of services have better chances to be alive.
  2. When you leave your activity you could save last timer value and last timestamp and restore timer with this info after activity is recreated.

PS. If you also want to fire the alarm when timer is finished you should use AlarmManager but keep in mind restrictions from android 6+ (M).

dilix
  • 3,761
  • 3
  • 31
  • 55