Search code examples
androidalarmmanagerandroid-pendingintent

Many PendingIntents, BroadcastReceiver and activity


I'm writing a simple reminder app. All reminders are stored in DB. I have a service that query DB and make a pendingIntents in AlarmManager with extras and different timestamps. Also I have a Broadcast Receiver to catch the Intents from AlarmManager. This Broadcast Receiver start a reminder Activity with options for reminder (dismiss, snooze, etc). Now this scheme work, but not as good as I think it should. If I have a reminder activity in foreground, then new reminder activity starts upon it (current goes to background). I want to not override the current activity with new one and just notify the user, that there are some new reminders that will show after the current.


Solution

  • As I think, I've found a good solution for my task:

    1) I've set in AndroidManifest that my reminder activity launchMode is "singleTop". More about launchMode is here http://developer.android.com/guide/topics/manifest/activity-element.html In two word, if my Broadcast Receiver tries to start activity that already on foreground, it calls onNewIntent, not onCreate.

    2) In my activity I've to override the onNewIntent method and store all incoming intents (from broadcast) in ArrayList .

    3) Before finish() I've to remove current Intent from ArrayList and when it's size become zero I've actually finish() the activity.

    One important addition. In broadcast receiver intent must have FLAG_ACTIVITY_SINGLE_TOP, like:

    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    Without it if no main activity present onNewIntent will not be called. As I see, this is knows issue: http://code.google.com/p/android/issues/detail?id=4155 Bug found in Android 1.6 and still present. So now it is feature :)

    Sorry for my English, it's easy for me to read, but hard to write :)