Android Question search example of a timer that does not stop when the smartphone is off

john mad doe

Member
Licensed User
Longtime User
Hello

For an app like a stopwatch, I need a timer that does not stop when the smartphone goes to sleep (screen off).

I understood that I had to launch a service to create the timer, but the problem is that it stops about 30 seconds after the smartphone goes to sleep.

I read that I had to write instructions like Service.AutomaticForegroundMode=Service.AUTOMATIC_FOREGROUND_ALWAYS but it doesn't solve my problem.

In fact I didn't really understand what to do, so I'm looking for an example.


Thanks for your help.
 

hatzisn

Well-Known Member
Licensed User
Longtime User
Use PhoneWakeState of Phone library. I don't remember the name of the method since I have closed the computer but it is the other than the method that keeps your screen from shutting off.
 
Upvote 0

Biswajit

Active Member
Licensed User
Longtime User
Check this tutorial how to use a background service that will run until you stop it manually
 
Upvote 0

JohnC

Expert
Licensed User
Longtime User
For apps that don't need to wake up the device (like a stopwatch app), one idea is to store the start time of the stopwatch in a file, then the device could even power completely off, and when your app runs again, it will simply calculate and display the time that pasted since the stored start time.
 
Upvote 0
Top