Search code examples
androidandroid-servicealarmmanagerandroid-alarms

Starting a service at regular intervals in android


My aim is to run a background service every 6 hours in the android application. What i have learnt from reading up is : I need to use alarmManager, setup alarms, receive those using broadcast receiver and then start my service in the onReceive method.

Now, i don't want to set the alarm for some particular time, as then all apps would send requests to the server at the same time. How do i get around this ? Also, most tutorials i read, registered the alarms in the onCreate of Activity. Wouldn't that lead to multiple registrations of the alarms, every time i start the app ? What would be the better place to do this.


Solution

  • You use

    http://developer.android.com/reference/android/app/AlarmManager.html#ELAPSED_REALTIME

    or

    http://developer.android.com/reference/android/app/AlarmManager.html#ELAPSED_REALTIME_WAKEUP

    which uses "time since boot" as a base, which is precisely for the case you're mentioning above.

    Also there is no multiple registration of the alarm, as long as the provided PendingIntent is the same.