PendingIntent的基本理解
PendingIntent可以看作是对Intent的一个封装,但它不是立刻执行某个行为,而是满足某些条件或触发某些事件后才执行指定的行为(启动特定Service,Activity,BrcastReceive)。我们可以把Pending Intent交给其他程序,其他程序按照PendingIntent进行操作。在Alarm定时器与Notification通知中都使用了PendingIntent
1. 获得PendingIntent类内部静态方法获得PendingIntent实例:
//获得一个用于启动特定Activity的PendingIntent
public static PendingIntent getActivity(Context context, int requestCode,Intent intent, int flags)
//获得一个用于启动特定Service的PendingIntent
public static PendingIntent getService(Context context, int requestCode,Intent intent, int flags)
//获得一个用于发送特定Broadcast的PendingIntent
public static PendingIntent getBroadcast(Context context, int requestCode,Intent intent, int flags)
参数说明:
- context:上下文对象。
- requstCode:请求码,发件人的私人请求代码(当前未使用)。
- intent:请求意图。用于要指明要启动的类以及数据的传递;
- flags:这是一个关键的标志位:
主要常量
- FLAG_CANCEL_CURRENT:如果当前系统中已经存在一个相同的PendingIntent对象,那么就将先将已有的PendingIntent取消,然后重新生成一个PendingIntent对象。
- FLAG_NO_CREATE:如果当前系统中不存在相同的PendingIntent对象,系统将不会创建该PendingIntent对象而是直接返回null。
- FLAG_ONE_SHOT:该PendingIntent只作用一次。在该PendingIntent对象通过send()方法触发过后,PendingIntent将自动调用cancel()进行销毁,那么如果你再调用send()方法的话,系统将会返回一个SendIntentException。
- FLAG_UPDATE_CURRENT:如果系统中有一个和你描述的PendingIntent对等的PendingInent,那么系统将使用该PendingIntent对象,但是会使用新的Intent来更新之前PendingIntent中的Intent对象数据,例如更新Intent中的Extras。
注意:两个PendingIntent对等是指它们的operation一样, 且其它们的Intent的action, data, categories, components和flags都一样。但是它们的Intent的Extra可以不一样。
本文由 创作,采用 知识共享署名4.0 国际许可协议进行许可。本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。最后编辑时间为: 2020/10/16 01:49