📚 开源资源分享——颜佐光的个人书架
✉️ 联系站长
书架 / Android / 语法

PendingIntent的基本理解

2020-10-16 09:49 · 约 1,779 字 · 浏览 2,465 次语法

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可以不一样。
← 返回《Android》目录书架 →