Search code examples
androidrecursionalarmmanagerintentservice

Recursive IntentService with AlarmManager


This is more or less a design question; but nonetheless. I have an IntentService that fires off a PendingIntent that calls itself every 15 minutes.

My question is, for the AlarmManager; should I be using either:

  • set(...) or
  • setRepeating(...)

The problem I noticed with setRepeating(...) is that I'll quickly get into an infinite loop, but I imagine this is because of the start time. If I use set(...); it works as expected without an infinite loop; the design question is should I be using setRepeating(...) over just adding a set(...) after every alarm call? If so, how can I do that without an infinite loop while having a recursive IntentService that calls itself each time the alarm goes off?


Solution

  • Both set and setRepeating are okay.

    set is easier to follow. You have the control over when your IntentService is launched next.

    I would recommend the use of setRepeating: why repeat yourself? For the infinite loop issue, save a boolean value in your SharedPreferences when you set the alarm. On the next launch of the IntentService, check the value. If its true, the alarm is already set. Else, this must be the first launch: set the repeating alarm.

    You will need to implement a receiver that listens for BOOT_COMPLETED action. When this intent is received, set the repeating alarm WITHOUT checking the SharedPreferences value. But DO set this value to true after issuing the setRepeating request.