Search code examples
androidhandleralarmschedule

handler or alarm in android service?


I have a service that run all time, and I need get Info from my server 2 times per day. must I use a Handler with 12Hs of delay? or an alarm?

can you tell me what is the best option please?

Thanks!


Solution

  • The AlarmManager was designed for exactly this kind of a task. It lets you set inexact alarms that Android will group with other tasks to minimize the battery cost associated with waking up the device. If you need to definitely poll the server at a precise time (and it cannot wait until the user wakes up the device), then you can set an exact alarm which will wake up the device and then you can have a method which will automate the creation of another exact alarm scheduled to be executed 12 hours from then.

    The drawback with AlarmManager is that the service will not automatically restart if the device turns off and is then turned back on. In this case, you can work around it by having a BroadcastReceiver listen to ACTION_BOOT_COMPLETE. Android 5.0 also provides the JobScheduler API which can persist jobs through system reboots.

    Handlers are best used for processes that run for a short time.