Reputation: 1680
In my project i have tried out some possibilities and limitations of PendingIntent
So i have created some notification, that opens an activity by tapping
Intent intent = new Intent(this, NotificationActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.putExtra(Constants.INTENT_ITEM_NAME, "ItemName");
intent.putExtra(Constants.INTENT_ITEM_ID, itemId);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
// properties set
;
notificationManager.notify(new Random().nextInt(10), notificationBuilder.build());
at begin was everithing good, until i have placed other item to show in NotificationActivity
by tap on notification.
Here starts problems: in NotificationActivity
was still showed previous item.
After some search it could be solved with:
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
BUT: if i have in same time many notifications, then i always see only last item, PendingIntent
was created for.
Second parameter of getActivity
is requestCode
. So when i update solution to
PendingIntent pendingIntent = PendingIntent.getActivity(this, new Random().nextInt(1000), intent, PendingIntent.FLAG_UPDATE_CURRENT);
Then also many items are supported, and if for some reason the random makes me same numbers, the content in NotificationActivity
will be the same.
So to 99% the solution is good, yes? NO
Again to first approach
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
If i set new extras for intent -> old extras will be readed.
In other words: by new Random().nextInt(1000)
somewhere in the system of android device will be stored till 1000 PendingIntents
for one of activities i have forever
So here are the questions:
With How to clear it, i mean a way to remove all currently maked PendingIntents
with some Random
as requestCode
, so that in clear way with only one notification at time i could use
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
with different items
Upvotes: 1
Views: 81
Reputation: 95578
PendingIntent
s are stored in non-persistent storage. When the device restarts, they are all gone.
Also, if you create a PendingIntent
and put it in a Notification
, once the Notification
is gone (dismissed, opened, etc.) the PendingIntent
is no longer in use and will be deleted.
Generally you should not use random numbers for the requestCode
as this is no guarantee of uniqueness. You need to find a way to make your PendingIntent
unique if you want to have many of them existing in parallel.
Upvotes: 1