Search code examples
androidandroid-intentalarmmanager

when alarm fires, start an activity if app active or send notification if app not active


In my app I want to schedule an Alarm associated with Activity A. When the alarm fires, what should happen depends on the circumstances:
1. if the app is not opened at that time, then display a notification in the notification bar and also start the activity A the next time the app is started
3. if the app is active, start Activity A

Activity A is not a background activity - it requires user interaction.

Ideally, the same behavior would work with more than 1 alarm - i.e. if 2 alarms fired while the app was not in use, two activities would be queued to start once the user starts the app.

I read the Android Docs on AlarmManager, PendingIntents and Notification - I know how to schedule an alarm which fires a notification, but I don't know at all how I would go about
- the "queueing" of activities after an alarm fires
- the "conditional behavior" when an alarm fires (based on whether app is running or not).

It seems like plenty of apps would need this kind of behavior. I hope someone can point me in the right direction.


Solution

  • Found a solution in the "Android Programming: The Big Nerd Ranch Guide" book (Hardy & Phillips). The solution is to use Intent Service that handles the AlarmManager intents, and sends an ordered broadcast. The broadcast is either received by an Activity, or - outside of the app lifetime - by another service, which then sends a notification.