From the documentation of Pending Intent FLAG_CANCEL_CURRENT
in Android:
by canceling the previous pending intent, this ensures that only entities given the new data will be able to launch it. If this assurance is not an issue, consider FLAG_UPDATE_CURRENT
Can anyone explain what this line means?
Once you create a new PendingIntent
with FLAG_CANCEL_CURRENT
, anything holding a previous PendingIntent
for the same Intent
will no longer be able to execute that original PendingIntent
.
For example, suppose we have this:
Intent i=new Intent(this, Foo.class);
i.putExtra("key", 1);
PendingIntent pi=PendingIntent.getActivity(this, 0, i, 0);
and we use that PendingIntent
with, say, a Notification
.
Later on, we execute:
Intent i=new Intent(this, Foo.class);
i.putExtra("key", 2);
PendingIntent pi2=PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
At this point, the PendingIntent
created originally (pi
) is no longer valid, and whatever we use pi2
for will see the updated extra value (2
).
If, instead, we did:
Intent i=new Intent(this, Foo.class);
i.putExtra("key", 2);
PendingIntent pi2=PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
At this point, pi
and pi2
both represent the same PendingIntent
, and both will see the updated extra value (2
).
Or, if we did:
Intent i=new Intent(this, Foo.class);
i.putExtra("key", 2);
PendingIntent pi2=PendingIntent.getActivity(this, 0, i, 0);
At this point, pi
and pi2
still represent the same PendingIntent
, but the extras are unchanged, as getActivity()
returns the original PendingIntent
without applying the new extras.
Most times, FLAG_UPDATE_CURRENT
is a fine answer when you are trying to replace extras inside a PendingIntent
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With