PendingIntent 延后启动 Activity/Service/Broadcast

省流:

client 封装真实intent到 PendingIntent ->
真正执行时 PendingIntent.send -> PendingIntentRecord.send & sendInner
-> ATMS.startActivityInPackage/startActivitiesInPackage/sendActivityResult/broadcastIntentInPackage/startServiceInPackage
即 xxxInPackage

1. 概念

PendingIntent:Intent的封装。
把这个封装好的intent交给别的程序,
别的程序根据这个intent延后处理intent中所描述的事情。

2. 三个方法:

getActivity(Context context, int requestCode, Intent intent, int flags, Bundle options)
getBroadcast(Context context, int requestCode, Intent intent, int flags)
getService(Context context, int requestCode, Intent intent, int flags)

3. PendingIntentRecord 向AMS 发起启动请求

最后通过 PendingIntentRecord 向AMS 发起启动请求, 调用AMS的对应方法 xxxInPackage(如startActivityInPackage)

源码:
frameworks/base/services/core/java/com/android/server/am/PendingIntentRecord.java

    public int sendInner(int code, Intent intent, String resolvedType, IBinder allowlistToken,
            IIntentReceiver finishedReceiver, String requiredPermission, IBinder resultTo,
            String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle options) {
            
            switch (key.type) {
                case ActivityManager.INTENT_SENDER_ACTIVITY:
                    ...             
                        if (key.allIntents != null && key.allIntents.length > 1) {
                            res = controller.mAtmInternal.startActivitiesInPackage(
                            ...
                        } else {
                            res = controller.mAtmInternal.startActivityInPackage(uid, callingPid,
                    ...         
                case ActivityManager.INTENT_SENDER_BROADCAST:
                        int sent = controller.mAmInternal.broadcastIntentInPackage(key.packageName,
                    ... 
                case ActivityManager.INTENT_SENDER_SERVICE:
                case ActivityManager.INTENT_SENDER_FOREGROUND_SERVICE:
                        controller.mAmInternal.startServiceInPackage(uid, finalIntent, resolvedType,                

其中: controller 是 PendingIntentController 对象,它的构造函数里,会去获取倒 ATMS 的本地代理对象, 即 ActivityTaskManagerInternal 对象

    PendingIntentController(Looper looper, UserController userController,
            ActivityManagerConstants constants) {
        mH = new Handler(looper);
        mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class);
        mUserController = userController;
        mConstants = constants;
    }

ActivityTaskManagerInternal 为 ATMS 的本地接口(system_server进程内部使用)

/**
 * Activity Task manager local system service interface.
 * @hide Only for use within system server
 */
public abstract class ActivityTaskManagerInternal { ...}

ActivityTaskManagerService 内部类 LocalService 实现了 ActivityTaskManagerInternal的接口,
并把LocalService 的对象添加到 LocalServices。

public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
    public ActivityTaskManagerService(Context context) {
        ...
        mInternal = new LocalService();
        ...

    public ActivityTaskManagerInternal getAtmInternal() {
        return mInternal;
    }
    
    private void start() {
        LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
    }
    
    final class LocalService extends ActivityTaskManagerInternal {
        @Override
        public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid..) {
            return getActivityStartController().startActivityInPackage(...)
        }
        @Override
        public int startActivityAsUser(IApplicationThread caller....) {
            return ActivityTaskManagerService.this.startActivityAsUser(     
    }   

因此, system_server 其它地方则可以通过 LocalServices.getService(ActivityTaskManagerInternal.class)
去获取到 ActivityTaskManagerInternal 的对象,
进而访问到 ATMS 或者直接处理。

4.参考:

PendingIntent源码分析: https://blog.csdn.net/konan1027/article/details/46914715
PendingIntentRecord 源码:
https://cs.android.com/android/platform/superproject/+/master:frameworks/base/services/core/java/com/android/server/am/PendingIntentRecord.java?hl=zh-cn

Android中pendingIntent的深入理解:https://blog.csdn.net/yuzhiboyi/article/details/8484771
Intent和PendingIntent的区别
a. Intent是立即使用的,而PendingIntent可以等到事件发生后触发,PendingIntent可以cancel
b. Intent在程序结束后即终止,而PendingIntent在程序结束后依然有效
c. PendingIntent自带Context,而Intent需要在某个Context内运行
d. Intent在原task中运行,PendingIntent在新的task中运行

5. 一个PendingIntent 执行的调用栈:

Client 调用AMS.sendIntentSender -> PendingIntentRecord.sendInner -> ActivityTaskManagerService.startActivityInPackage
->ActivityStartController.startActivityInPackage
-> ActivityStarter.execute/executeRequest
则会执行 start u

07-06  18:49:42.134  E  1876   5896      at com.android.server.wm.ActivityStarter.executeRequest(ActivityStarter.java:1197)
07-06  18:49:42.134  E  1876   5896      at com.android.server.wm.ActivityStarter.execute(ActivityStarter.java:1026)
07-06  18:49:42.134  E  1876   5896      at com.android.server.wm.ActivityStartController.startActivityInPackage(ActivityStartController.java:425)
07-06  18:49:42.134  E  1876   5896      at com.android.server.wm.ActivityTaskManagerService$LocalService.startActivityInPackage(ActivityTaskManagerService.java:6926)
07-06  18:49:42.134  E  1876   5896      at com.android.server.am.PendingIntentRecord.sendInner(PendingIntentRecord.java:586)
07-06  18:49:42.134  E  1876   5896      at com.android.server.am.ActivityManagerService.sendIntentSender(ActivityManagerService.java:6579)
07-06  18:49:42.134  E  1876   5896      at com.android.server.am.ActivityManagerService.sendIntentSender(ActivityManagerService.java:6568)
07-06  18:49:42.134  E  1876   5896      at android.app.IActivityManager$Stub.onTransact(IActivityManager.java:4856)
07-06  18:49:42.134  E  1876   5896      at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:3135)
07-06  18:49:42.134  E  1876   5896      at android.os.Binder.execTransactInternal(Binder.java:1316)
07-06  18:49:42.134  E  1876   5896      at android.os.Binder.execTransact(Binder.java:1280)

6. 获取PendingIntent 对象 源码

以获取Activity 的PI 对象为例,
可见有两个方法,分别为 getActivity 和 getActivityAsUser, 前者是公开,后者是hide的。
后者可以传入 当前 user。
前者默认的user 是通过传入的 context 去获取的。

    @SuppressWarnings("AndroidFrameworkPendingIntentMutability")
    public static PendingIntent getActivity(Context context, int requestCode,
            @NonNull Intent intent, @Flags int flags, @Nullable Bundle options) {
        // Some tests only mock Context.getUserId(), so fallback to the id Context.getUser() is null
        final UserHandle user = context.getUser();
        return getActivityAsUser(context, requestCode, intent, flags, options,
                user != null ? user : UserHandle.of(context.getUserId()));
    }

    /**
     * @hide
     * Note that UserHandle.CURRENT will be interpreted at the time the
     * activity is started, not when the pending intent is created.
     */
    @UnsupportedAppUsage
    public static PendingIntent getActivityAsUser(Context context, int requestCode,
            @NonNull Intent intent, int flags, Bundle options, UserHandle user) {
        String packageName = context.getPackageName();
        String resolvedType = intent.resolveTypeIfNeeded(context.getContentResolver());
        checkFlags(flags, packageName);
        try {
            intent.migrateExtraStreamToClipData(context);
            intent.prepareToLeaveProcess(context);
            IIntentSender target =
                ActivityManager.getService().getIntentSenderWithFeature(
                    INTENT_SENDER_ACTIVITY, packageName,
                    context.getAttributionTag(), null, null, requestCode, new Intent[] { intent },
                    resolvedType != null ? new String[] { resolvedType } : null,
                    flags, options, user.getIdentifier());
            return target != null ? new PendingIntent(target) : null;
        } catch (RemoteException e) {
            throw e.rethrowFromSystemServer();
        }
    }

--- End ---

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 196,302评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,563评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,433评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,628评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,467评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,354评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,777评论 3 387
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,419评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,725评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,768评论 2 314
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,543评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,387评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,794评论 3 300
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,032评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,305评论 1 252
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,741评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,946评论 2 336