Remove data from notification intent

EDIT: I’ve created a sample application to test this problem and possible solutions. Here are my findings:

If you launch your app from a notification with extras and then later return to your app by selecting it from the list of recent tasks, Android will launch the app again the same way it was launched from the notification (ie: with the extras). This is either a bug or a feature, depending on who you ask.

You’ll need to add additional code to deal with this situation. I can offer 2 suggestions:

1. Use FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS

When you create your notification, set the flag Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS in the Intent. Then, when the user selects the notification and launches the app from the notification, this will not create an entry for this task in the list of recent tasks. Also, if there was an entry in the list of recent tasks for this application, that entry will also be removed. In this case, it will not be possible for the user to return to this task from the list of recent tasks. This solves your problem by removing the possibility that the user launches the app from the list of recent tasks (but only when the app has been launched from the notification).

2. Detect FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY

When the user launches your app from the list of recent tasks, Android sets the flag Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY in the Intent that is passed to onCreate() of your launch activity. You can detect the presence of this flag in onCreate() and then you know that the app has been launched from the recent tasks list and not from the notification. In this case, you can just ignore the fact that the extras in the Intent still contain data.

Choose the solution that best suits the workflow for your application. And thanks for the question, this was an interesting challenge to solve 🙂


Additional information:

You are creating the PendingIntent incorrectly. You are calling

PendingIntent contentIntent = PendingIntent.getActivity(this,
        TripLoggerConstants.PENDING_TRIPS_NOTIFICATION_ID,
        new Intent(this, MainActivity.class).putExtra("is_log", true),
        Intent.FLAG_ACTIVITY_CLEAR_TOP);

You are passing Intent.FLAG_ACTIVITY_CLEAR_TOP as the 4th parameter to getActivity(). However, that parameter should be PendingIntent flags. If you want to set FLAG_ACTIVITY_CLEAR_TOP on the Intent, you need to do it this way:

PendingIntent contentIntent = PendingIntent.getActivity(this,
        TripLoggerConstants.PENDING_TRIPS_NOTIFICATION_ID,
        new Intent(this, MainActivity.class).putExtra("is_log", true)
        .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP), 0);

Leave a Comment