mahela007
mahela007

Reputation: 1439

android: Timer for Quiz app

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

Answers (3)

Varun Oberoi
Varun Oberoi

Reputation: 692

Just listing down possible ways it could be implemented (best one first):

  1. user2553764' s answer of just saving & calculating timer value based on system. (Best suited, it is simple & requires no background services or threads).

  2. 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).

  3. 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).

  4. 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

Masaharta
Masaharta

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)

  • stop the timer
  • store the current time

Override OnResume() method (called when activity returns in foreground)

  • compute the elapsed delay
  • if the timer has expired : display message
  • else restart the countdown timer with remaining seconds

Upvotes: 2

Gabe Sechan
Gabe Sechan

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

Related Questions