A few concepts ...
Sleep mode
The Android kernel will go into sleep mode (by default), if no user interaction or WAKE_LOCK
are 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_LOCK
and 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_LOCK
when service starts. Just don't forget that you will pay that in battery live.
Note:
Dosen't matter if you use a Timer
, Handler
or anything else, the above will always apply.
Regards.