Clarification on the docs for PendingIntent.FLAG_CANCEL_CURRENT

后端 未结 1 1726
挽巷
挽巷 2020-12-30 10:53

From the documentation of Pending Intent FLAG_CANCEL_CURRENT in Android:

by canceling the previous pending intent, this ensures that only entities giv

相关标签:
1条回答
  • 2020-12-30 11:53

    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.

    0 讨论(0)
提交回复
热议问题