Search code examples
androidandroid-intentalarmmanager

Pending Intent types and the Alarm Manager


I would like to set an alarm that will fire off once.

There is a pendingintent flag named OneShot. It looks like that would be the right flag to use.

But do I need to use that flag? If I use AlarmManager.SetTime(), then it should not repeat.

What does OneShot offer?


Solution

  • I think you're asking the difference between scheduling an alarm one time, via AlarmManager.set (not setTime?) and the use of PendingIntent.FLAG_ONE_SHOT.

    First understand that a PendingIntent is a license to act as your app with your apps perms at some point in the future. From the PI docs: "The returned object can be handed to other applications so that they can perform the action you described on your behalf at a later time."

    If you just use AlarmManager.set ONCE, then yes, your PendingIntent will only be fired once, but whatever captures it can use it more than once, unless you send it with a "one shot" flag. Now, if "whatever captures it" is also your own app, then it's probably not a big deal (you are unlikely to abuse your own future self ;)). Still, if it's a PendingIntent that you think should only ever be used once, it's probably just safer to go ahead and use the one shot flag anyway.

    To sum up the difference, setting FLAG_ONE_SHOT sends the permissions to use the PI only once with the PI, versus only firing it off once with AlarmManager. How many times you fire the alarm, and what the permissions of the PI are, are two different things.