Android 12 startActivity梳理

前面梳理了WM中Window容器的概念,今天梳理一下startActivity的流程,看一下window容器的体现。

其实在server端Window最终都会表现为WindowState对象。而之所以存在划分层级的window容器,是为了有层级的管理,目的是实现Android的一些列feature,如:

  • 任务栈Task,Task引出Activity的生命周期
  • window focus,这个对于input子系统很重要
  • 多Display支持
  • 多Window支持

1、时序

# 1
Activity.startActivity
    Activity.startActivityForResult
        Instrumentation.execStartActivity
            ActivityTaskManagerService.startActivity
                ActivityTaskManagerService.startActivityAsUser
                    ActivityStarter.execute ->

# 2
->
ActivityStarter.execute
    Request.resolveActivity
        ActivityTaskSupervisor.resolveIntent
        ActivityTaskSupervisor.resolveActivity
    RootWindowContainer.getTopDisplayFocusedRootTask
    ActivityStarter.executeRequest
        ActivityStarter.startActivityUnchecked
            ActivityStarter.startActivityInner
                ActivityStarter.setInitialState
                ActivityStarter.computeLaunchingTaskFlags
                ActivityStarter.computeSourceRootTask
                Task.startActivityLocked
                RootWindowContainer.resumeFocusedTasksTopActivities
                    Task.resumeTopActivityUncheckedLocked
                        Task.resumeTopActivityInnerLocked
                            ActivityTaskSupervisor.startSpecificActivity
                                ActivityTaskSupervisor.realStartActivityLocked
                                    ClientLifecycleManager.scheduleTransaction ->

# 3
->
ClientLifecycleManager.scheduleTransaction
    ClientTransaction.schedule
        ApplicationThread.scheduleTransaction
            ClientTransactionHandler.scheduleTransaction        // 具体实现是 ActivityThread
                ActivityThread.H.handleMessage
                    TransactionExecutor.execute
                        TransactionExecutor.executeCallbacks
                            TransactionExecutor.cycleToPath
                                TransactionExecutor.performLifecycleSequence
                                    ActivityThread.handleLaunchActivity ->

# 4
->
ActivityThread.handleLaunchActivity
    ActivityThread.performLaunchActivity
        Instrumentation.newActivity                        // new 一个 Activity
            AppComponentFactory.instantiateActivity
        LoadedApk.makeApplication
            Instrumentation.newApplication
                Instrumentation.callApplicationOnCreate
        Activity.attach                        // Activity初始化
            FragmentController.attachHost
            new PhoneWindow                    // new 一个 PhoneWindow,其中会填充DecorView,DecorView是在onResume时,
                                               // 在Activity.makeVisible方法中被addView的
                Window.setWindowManager
        Instrumentation.callActivityOnCreate
            Activity.performCreate
                Activity.onCreate            // 回调 onCreate

分阶段说明

  1. app端发起startActivity的请求,system server会将请求交给ATMS处理,然后由ActivityStarter执行

  2. server端start Activity具体流程,包括:

    • 解析Intent
    • 处理launch flags,对应app端的launch mode
    • 权限校验
    • 按照Window层级,最终使Task去执行start Activity
    • server处理好后,通过Binder通知app端执行相应业务
  3. Binder通信:通过IApplicationThread(app实现,server调用它的代理)接口通知app端launch Activity。
    app/server之间,Activity各个生命周期的通信都封装成了事务处理的工具类,传递的对象是ClientTransaction,
    两端分别是server的ClientLifecycleManager 和 app的ClientTransactionHandler

  4. app端执行launch Activity,包括:

    • new Activity,并初始化
    • (如果没有创建Application)new Application,并回调其onCreate方法
    • 回调Activity的onCreate

2、核心代码摘要

// ActivityStarter.java
private int executeRequest(Request request) {
    final IBinder resultTo = request.resultTo;
    
    // AM通过ProcessRecord管理进程。
    // WM为例管理windows&activities,需要知道进程信息,WindowProcessController负责将AM端的进程信息、状态传递给WM。
    // 获取caller信息,后面的校验&startActivity等需要caller的信息。
    WindowProcessController callerApp = null;
    if (caller != null) {
        callerApp = mService.getProcessController(caller);
        if (callerApp != null) {
            callingPid = callerApp.getPid();
            callingUid = callerApp.mInfo.uid;
        } else {
            Slog.w(TAG, "Unable to find app for caller " + caller + " (pid=" + callingPid
                    + ") when starting: " + intent.toString());
            err = ActivityManager.START_PERMISSION_DENIED;
        }
    }
    
    ActivityRecord sourceRecord = null;
    ActivityRecord resultRecord = null;
    if (resultTo != null) {
        sourceRecord = mRootWindowContainer.isInAnyTask(resultTo);
        if (DEBUG_RESULTS) {
            Slog.v(TAG_RESULTS, "Will send result to " + resultTo + " " + sourceRecord);
        }
        if (sourceRecord != null) {
            if (requestCode >= 0 && !sourceRecord.finishing) {
                resultRecord = sourceRecord;
            }
        }
    }
    
    // 处理 launch flags
    final int launchFlags = intent.getFlags();
    ......
       
    // 权限检查
    boolean abort = !mSupervisor.checkStartAnyActivityPermission(intent, aInfo, resultWho,
            requestCode, callingPid, callingUid, callingPackage, callingFeatureId,
            request.ignoreTargetSecurity, inTask != null, callerApp, resultRecord,
            resultRootTask);
    abort |= !mService.mIntentFirewall.checkStartActivity(intent, callingUid,
            callingPid, resolvedType, aInfo.applicationInfo);
    abort |= !mService.getPermissionPolicyInternal().checkStartActivity(intent, callingUid,
            callingPackage);
    
    final ActivityRecord r = new ActivityRecord.Builder(mService)
            .setCaller(callerApp)
            ......
            .setSourceRecord(sourceRecord)
            .build();
    
    // 实际 startActivity
    mLastStartActivityResult = startActivityUnchecked(r, sourceRecord, voiceSession,
            request.voiceInteractor, startFlags, true /* doResume */, checkedOptions, inTask,
            restrictedBgActivity, intentGrants);

    return mLastStartActivityResult;
}
// ActivityStarter.java
// 通知RootWindowContainer和Task等容器处理之前的逻辑
int startActivityInner(final ActivityRecord r, ActivityRecord sourceRecord,
        IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
        int startFlags, boolean doResume, ActivityOptions options, Task inTask,
        boolean restrictedBgActivity, NeededUriGrants intentGrants) {
    setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession,
            voiceInteractor, restrictedBgActivity);
    computeLaunchingTaskFlags();
    computeSourceRootTask();
	......
    mTargetRootTask.startActivityLocked(mStartActivity,
            topRootTask != null ? topRootTask.getTopNonFinishingActivity() : null, newTask,
            mKeepCurTransition, mOptions, sourceRecord);
    ......
    mRootWindowContainer.resumeFocusedTasksTopActivities(
                        mTargetRootTask, mStartActivity, mOptions, mTransientLaunch);
    ......
}

private void setInitialState(ActivityRecord r, ActivityOptions options, Task inTask,
        boolean doResume, int startFlags, ActivityRecord sourceRecord,
        IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
        boolean restrictedBgActivity) {
    
    // 计算task边界?
    // Preferred display id is the only state we need for now and it could be updated again
    // after we located a reusable task (which might be resided in another display).
    mSupervisor.getLaunchParamsController().calculate(inTask, r.info.windowLayout, r,
            sourceRecord, options, mRequest, PHASE_DISPLAY, mLaunchParams);
    // 获取TaskDisplayArea
    mPreferredTaskDisplayArea = mLaunchParams.hasPreferredTaskDisplayArea()
            ? mLaunchParams.mPreferredTaskDisplayArea
            : mRootWindowContainer.getDefaultTaskDisplayArea();
    mPreferredWindowingMode = mLaunchParams.mWindowingMode;
    
    mInTask = inTask;
}

private void computeLaunchingTaskFlags() {
    // mInTask 是即将被添加ActivityRecord的Task
    // 目的是初始化mAddingToTask
    if (mSourceRecord == null && mInTask != null && mInTask.getRootTask() != null) {
        
    } else {
        
    }
    if (mInTask == null) {
        // 根据不同的情况,添加new task的标记位。
        mLaunchFlags |= FLAG_ACTIVITY_NEW_TASK;
    }
}

posted on 2023-05-30 13:49  luke4212  阅读(94)  评论(0编辑  收藏  举报

导航