Reputation: 1439
I'm involved in developing a Quiz app for android. Each collection of questions should be answered within a specified period of time. This period of time can be measured using an android CountDownTimer.
However, CountDownTimer pauses when the app is no longer in focus. What should I do if I want to timer to continue running, even if the app is closed? (If the app is reopened and the timer has expired, the app should display a suitable message).
Upvotes: 1
Views: 872
Reputation: 692
Just listing down possible ways it could be implemented (best one first):
user2553764' s answer of just saving & calculating timer value based on system. (Best suited, it is simple & requires no background services or threads).
Using handler, see How to set a timer in android. (Official documentation suggests it use for timed operations, though seem overkill for your use case).
Using a Service (bindservice), Implementing a Count down timer using Service in the background. (But services can go out of memory, in that case might have to use it with 1st approach).
AlarmManager, dunno if it should be below binded service but it can be used none the less. How to run a method every X seconds, suggests use AlarmManager for >10min intervals else Handlers. (Also mentioned in android documentation as you stated above).
Upvotes: 1
Reputation: 104
Use the lifecycle of your Activity http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
Override OnPause() method (called when activity loose focus)
Override OnResume() method (called when activity returns in foreground)
Upvotes: 2
Reputation: 93678
You want to create an Alarm using AlarmManager. They run regardless of what activity is on screen, and even runs when the phone is asleep.
Upvotes: 0