Search code examples
androidandroid-alarms

Running task periodicaly(once a day/once a week)


I want to run some task (i.e. get my web site news page) periodically (once a week/ a day), even if my application is closed. Is it possible?


Solution

  • Yes it is, you need to look at the AlarmManager to setup a reoccurring "Alarm". This is better for battery life on the device, as unlike a service it does not run constantly in the background. The Alarm triggers a broadcast receiver which will execute your custom code.

    As a final note - there are enum values for the timing of the Alarm including daily, half daily and many more although you can just set an actual value.

    A good example can be found in the follow SO post:

    Alarm Manager Example

    Update

    Newer features have been added to Android. If you are reading this then I would advise you now look into GcmNetworkManager. This optimises battery life and works pre-lollipop. For Lollipop onwards you can use JobScheduler. I would advise using these classes over the AlarmManager.