Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getIntent() in onResume() always returns same action, how to consume it?

I'm showing a notification with an intent like this:

Intent intentOpen = new Intent(this, MainActivity.class);
intentOpen.setAction("ACTION_SHOW_BACKUP_FRAGMENT");
intentOpen.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntentOpen = PendingIntent.getActivity(this, 0, intentOpen, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.setContentIntent(pendingIntentOpen);

As you can see, the action is set to "ACTION_SHOW_BACKUP_FRAGMENT", so that when the user clicks in the notification, my singleTop MainActivity can get the action in the onResume() method with getIntent().getAction().

In order for this to work I had to implement onNewIntent() like this:

protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    setIntent(intent);
}

So far, so good, the action is received and I can show the backup view. But then if I press the home button, so that the app goes to the background, and then enter on it again via the recent apps menu, the onResume() method is called again but the "ACTION_SHOW_BACKUP_FRAGMENT" action is still there! So I cannot differentiate if the user really clicked on the notification or is just resuming the app.

I have tried solving the issue with a log of combinations of Intent and PendingIntent flags but nothing worked. I also tried calling setIntent(new Intent()); after using the action in onResume() but onNewIntent() still gets the "ACTION_SHOW_BACKUP_FRAGMENT" action the next time I resume the app.

How can I solve this issue?

like image 764
cprcrack Avatar asked Oct 20 '22 06:10

cprcrack


1 Answers

Finally I found the right combination of flags for the Intent and PendingIntent:

// Create pending intent to open the backup fragment
intentOpen.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntentOpen = PendingIntent.getActivity(this, 0, intentOpen, PendingIntent.FLAG_CANCEL_CURRENT);

This works while I still consume the intent in onResume() with setIntent(null);

like image 134
cprcrack Avatar answered Oct 27 '22 11:10

cprcrack