6

When I click the notification on the status bar it launches an activity but the behavior is strange. If my app is in foreground and I click the notification the notification intent is fired once. If my app is in background then the notification intent is fired twice. If I exit the app (ie all activities have been popped by hitting the back button) then notification intent is fired once. Can anyone explain this behaviour. The code snippet is as follows:

_notification = new Notification(icon_id, "Ticker Text", System.currentTimeMillis());
_showActivityIntent = new Intent();
_showActivityIntent.setAction(MyActivityName);
_showActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK + Intent.FLAG_ACTIVITY_NO_HISTORY);
_showActivityPendingIntent = PendingIntent.getActivity(context, 0, _showActivityIntent, 0);
_notification.setLatestEventInfo(context, "My title", "My text", _showActivityPendingIntent);
_notificationMgr.notify(notificationId, _notification);
skaffman
  • 398,947
  • 96
  • 818
  • 769
pankajagarwal
  • 13,462
  • 14
  • 54
  • 65

2 Answers2

9
_showActivityIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

Try this. it will prevent multiple instances of the same activity. u can put this in the manifest also

Varun
  • 33,833
  • 4
  • 49
  • 42
  • 2
    I'll try it out, but can you explain why the same activity is being launched twice ? – pankajagarwal Dec 02 '10 at 11:34
  • http://developer.android.com/guide/topics/fundamentals.html#acttask . if you read the documentation it clearly says what every flag does. – Varun Dec 03 '10 at 05:49
  • But why are the 2 being launched in the first place. This seems like a work around, not a fix. – Kelly Merrell Oct 31 '14 at 19:16
  • 1
    This not a workaround. They are launched twice because that is the default behavior. You can create multiple intents and have multiple instances of the same activityclass. And thats not what is needed, then the flags are there to help. Read through how processes and back stacks work - http://developer.android.com/guide/components/tasks-and-back-stack.html – Varun Nov 01 '14 at 04:03
0

None of the flags worked:

  Intent().apply {
            addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
            addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            ...

You need to add in the Manifest for that activity:

android:launchMode="singleTask"
android:taskAffinity=""
android:excludeFromRecents="true"

Check: https://developer.android.com/develop/ui/views/notifications/navigation

Dan Alboteanu
  • 9,404
  • 1
  • 52
  • 40