PendingIntent详解

 Intent是一个意图,一个描述了想要启动一个Activity、Broadcast或是Service的意图。它主要持有的信息是它想要启动的组件(Activity、Broadcast或是Service),在开发操作中,需要通过 startActivity , startService 或sendBroadcast 方法来启动这个意图执行某些操作!!

  PendingIntent可以认为是对Intent的包装,实际上就是,供当前App或之外的其他App调用,而常见的是供外部App使用,外部App执行这个 PendingIntent时,间接地调用里面的Intent,即外部App延时执行PendingIntent中描述的Intent及其最终行为,PendingIntent主要持有的信息是它所包装的Intent和当前App Context,即使当前App已经不存在了,也能通过存在于PendingIntent里的 Context来执行Intent。当你把PendingIntent递交给别的程序进行处理时,PendingIntent仍然拥有PendingIntent原程序所拥有的权限,当你从系统取得一个PendingIntent时,一定要非常小心才行,比如,通常,如果Intent目的地是你自己的component(Activity/Service/BroadcastReceiver)的话,你最好采用在Intent中显示指定目的component名字的方式,以确保Intent最终能发到目的,否则Intent最后可能不知道发到哪里了。

可以这样理解:当你想在Aactivity中启动另一个Bactivity,那么你可以选择两种情况[立即启动或延时启动]:
1.通过intent配置需要启动的Bactivity,然后调用startActivity()方法,让他立即执行启动操作,跳转过去
2.另一种情况是,你虽然想启动另一个Bactivity,可是你并不想马上跳转到Bactivity页面,你想静等5分钟之后再跳转到Bactivity,那么你可以通过PendingIntent来实现[当然实现方式有很多啦,这里仅是想说明PendingIntent与intent的区别],PendingIntent可以包装第1步中的intent,然后通过AlarmManager这个定时器,定制5分钟之后启PendingIntent,实现这种延时操作,如果你还是听着似懂非懂,一头雾水,我表示很有压力了,我该怎么说你才能清楚呢,理论终究是抽象的,后见将会通过一个程序说明一下,程序中是启动一个BroadcastReceiver,其实原理都是一样的!!

如何获得一个PendingIntent呢?其实很简单:
1.你可以通过getActivity(Context context, int requestCode, Intent intent, int flags)系列方法从系统

取得一个用于启动一个Activity的PendingIntent对象
2.可以通过getService(Context context, int requestCode, Intent intent, int flags)方法从系统取得一个

用于启动一个Service的PendingIntent对象
3.可以通过getBroadcast(Context context, int requestCode, Intent intent, int flags)方法从系统取得一

个用于向BroadcastReceiver的发送广播的PendingIntent对象

PendingIntent几个常量:

1.FLAG_CANCEL_CURRENT :如果AlarmManager管理的PendingIntent已经存在,那么将会取消当前的

PendingIntent,从而创建一个新的PendingIntent
2.FLAG_UPDATE_CURRENT:如果AlarmManager管理的PendingIntent已经存在,可以让新的Intent更新之前

PendingIntent中的Intent对象数据,例如更新Intent中的Extras,另外,我们也可以在PendingIntent的原进程

中调用PendingIntent的cancel ()把其从系统中移除掉
3.FLAG_NO_CREATE :如果AlarmManager管理的PendingIntent已经存在,那么将不进行任何操作,直接返回已经

存在的PendingIntent,如果PendingIntent不存在了,那么返回null

原文地址:https://www.cnblogs.com/cliuwei/p/5977852.html