已经有了 Intent,那为啥还要 PendingIntent?

摘录自已经有了 Intent,那为啥还要 PendingIntent?

使用场景

1.Intent            
@startActivity sendBroadcast startService
@Intent通常是在启动Activity、发广播、启动Service的时候
2.PendingIntent     
@AlarmManager、Notification/NotificationManager、RemoteViews/AppWidgetManager
@在使用AlarmManager创建定时任务,或者给Notification、RemoteViews设置点击事件时都会用到
@对于Intent的使用场景,PendingIntent也有对应的静态方法:getActivity、getBroadcast、getService,
它们的作用分别是(在触发时):startActivity、sendBroadcast、startService

主要区别是在创建PendingIntent对象时是跟system_process(系统服务进程,AMS、PMS、WMS都在这个进程)有互动的

image.png

  在调用PendingIntent那几个静态方法来创建PendingIntent对象时,会将传进去的Intent以及其他参数通过Binder
传输到【系统服务进程】那边,接着,AMS会调用PendingIntentController的`getIntentSender`方法创建一个
对应的PendingIntentRecord实例,而那些从App传过来的参数,都会保存在PendingIntentRecord.`key`里面,
最后会把PendingIntentRecord实例`add`到`mIntentSenderRecords`中并返回。
  当我们拿到PendingIntent对象之后,它里面的`mTarget`已经初始化完成了,也就是一个IIntentSender
(AIDL接口)的Proxy的引用
  一旦我们调用PendingIntent.`send`,【系统服务进程】那边对应的PendingIntentRecord实例的`send`方
法就会被调用,它会根据`type`(PendingIntent那几个静态方法`getActivity`、`getBroadcast`等,已经帮
我们选择好了Type,比如`getActivity`的`type`是*INTENT_SENDER_ACTIVITY*,`getService`是
*INTENT_SENDER_SERVICE*)来作出不同的动作。看到那个PendingIntentRecord的内部类Key了吗,它里面的
`requestIntent`,就是我们一开始往PendingIntent传的那个Intent!在`startActivity`或`sendBroadcast`、
`startService`的时候,它就派上用场了!

因为PendingIntent的相关数据都保存在【系统服务进程】,那么就算创建这个对象的进程已经被kill了,只要这个PendingIntent对象还存在,那它还是能够起到作用的。

为什么会说创建PendingIntent对象的进程被kill,PendingIntent对象还能存在呢?

PendingIntent是实现了Parcelable的,也就是可以跨进程传输。比如我们常见的:给Notification设置点击事
件,Notification就会带着PendingIntent一起被传过NotificationManager那边,最终放到`com.android.
systemui`进程里,当通知被点击的时候,就会触发它的`send`方法。

你可能感兴趣的:(已经有了 Intent,那为啥还要 PendingIntent?)