Reputation: 151
I know the concept of pending intent but the flags are confusing.
Even android documentation is very hard to understand
Can someone provide explanation of pending intent flags particularly FLAG_ONE_SHOT
and FLAG_NO_CREATE
with examples?
Upvotes: 3
Views: 1598
Reputation: 95628
PendingIntent
s are managed by the Android framework. When you call one of the PendingIntent.getXXX()
methods, the framework tries to find an existing PendingIntent
that matches the parameters you pass to the getXXX()
method. If it finds a matching PendingIntent
it will just return that to the caller. If it doesn't find a matching PendingIntent
it will (usually) create a new PendingIntent
and return that to the caller. You can alter this standard behaviour by using the flags:
FLAG_NO_CREATE
is used to get an existing PendingIntent
. If a matching PendingIntent
exists, it will be returned to the caller. If no matching PendingIntent
exists, nothing happens. The framework will not create a new PendingIntent
and the method returns null
to the caller. You can use this method to determine if a specific PendingIntent
exists. You can also use this method to get an existing PendingIntent
so that you can cancel it.
FLAG_ONE_SHOT
is strange. According to the documentation, this flag should cause the PendingIntent
to be deleted after it is used (sent). However, there are other side-effects of this flag. For example, if you create a PendingIntent
using this flag, and then try to get this PendingIntent
(or test the existence of it) by calling PendingIntent.getXXX()
with FLAG_NO_CREATE
, the framework will always return null
. For this reason I never use it and I also recommend that it never be used.
FLAG_CANCEL_CURRENT
is used to delete an existing PendingIntent
and create a new one. The framework first tries to find a matching PendingIntent
. If it finds one, it cancels (deletes) this PendingIntent
. That means that any applications holding this PendingIntent
will not be able to trigger (send) it. The framework then creates a new PendingIntent
with the provided parameters and returns this to the caller.
FLAG_UPDATE_CURRENT
is used to update an existing PendingIntent
. The framework first tries to find a matching PendingIntent
. If it finds one, the "extras" in the existing PendingIntent
are overwritten with the "extras" in the provided Intent
parameter. If no matching PendingIntent
is found, a new one is created with the provided parameters. The found (or newly created) PendingIntent
is returned to the caller.
NOTE: See this answer for information on how the Android framework tries to find a "matching" PendingIntent
: https://stackoverflow.com/a/29590084/769265
Upvotes: 3