user16655
user16655

Reputation: 1941

Timer in Android - how to keep counting even when phone or app is off

I am trying to implement a timer that just counts the time passed since pressed start. I need to keep this counter even if the app/phone is off. How do I achieve this? Store the current time somewhere when the app is turned off, and then retrieve this data when the app is on again? And if this is a good way to do it, how do I implement this solution? I hope someone has some input.

I have implemented my timer/counter using Handler (I saw this solution in an answer here on StackOverflow)

Upvotes: 0

Views: 1828

Answers (3)

Alex Crist
Alex Crist

Reputation: 1099

One method of doing this would be to save the system Time when the counter begins and then again save the Time when it ends.

You can compare the start time with the end time to find out how much time has passed.

It might look something like this:

Calendar c = Calendar.getInstance();
int startTime = c.get(Calendar.SECOND);

...

Calendar c = Calendar.getInstance();
int endTime = c.get(Calendar.SECOND);

int secondsElapsed = endTime - startTime;

Edit: The main downside of this method is that it does not account for timezone changes or changes to system time. If neither of those concern you, it works fine.


Edit 2: To save the startTime so it isn't lost when the app is closed, use SharedPreferences. An example of storing and retrieving values with SharedPreferences can be seen here.

Upvotes: 2

Jim
Jim

Reputation: 10278

if you are really worried about the time since "start" was pressed, you need probably need elapsedRealtime - system clock can be manipulated, but even elapsed time is reset with the restart of the phone, so be cautious, but that should do most of what you need.

See this post: Know if uptime timer is reset or Android has been rebooted

Upvotes: 1

Viacheslav
Viacheslav

Reputation: 5593

You should use Alarm Manager. It utilize PendingIntent to send notification to your app's components, for example to BroadcastReceiver where you can process delayed job.

Upvotes: 0

Related Questions