Well this question is basicly similiar to what i ask, i tried to use a Timer on a Service that runs a runnable every 1 second that this runnable updates some UI in some other Activity.
This activity can be on background or dead, but the service must not stop counting down, as the guy in the added question said, I too sometimes get all the runnables run at once when i wake my phone up.
The Answer he got was Use AlarmManager, but Android docs discourages the use of AlarmManager for timeouts and ticks, and suggested using a handler, So anybody got an exemple of how its done correctly using handler?
Note that the problems begin to accure when the Phone goes to sleep and only after a while, Timer works good for like 30 mins, but for few hours it doesnt…
A few concepts …
Sleep mode
The Android kernel will go into sleep mode (by default), if no user interaction or
WAKE_LOCKare request. This is done to minimized battery utilization, and means that any code will stop running.Alarm Manager
This is an API that can set a timmer event to awake kernel and start running code. If an application needs to perform some long activity, it should request a wake lick, otherwise the kernel will go again into sleep mode in a short period of time.
Whats going on with your application
Your service is stopped as soon as the device goes into sleep. When the device is awaked by the user or by some alarm manager request made by some other application in your phone, your service starts again. When phone goes into sleep again, so goes your service.
What you should do
First of all, you should think carefully if you really need to have the update going on when the phone is not being used for some time (when it should be put into sleep mode). Maybe no one is using it, and having the service running continously, will keep drainning battery.
If you don’t need the service to run continously, you have 2 options:
Use Alarm Manager
To wakeup the device at fixed interval times (use the less frequency possible) and update you service work. If this takes some time, request a
WAKE_LOCKand release it after completion.Use Last
If you can wait for the phone to be awaked by the user to update you service work is even better. Just drop all update request with exception of last one.
Finally
If you really need the service to run continously, request a
WAKE_LOCKwhen service starts. Just don’t forget that you will pay that in battery live.Note:Dosen’t matter if you use aTimer,Handleror anything else, the above will always apply.Regards.