【Android】Framework笔记——Activity 启动流程简述

晚上抓住最后一点时间,来重新对 Activtiy 启动流程的源码进行一次梳理。

本启动流程分析基于 Android 9.0

客户端

我们启动一个 Activity,往往需要先构建一个 Intent,之后调用 Activity.startActivity 进行 Activity 的启动:

@Override
public void startActivity(Intent intent) {
    this.startActivity(intent, null);
}

startActivity 又调用到了 startActivity(Intent, Bundle)

@Override
public void startActivity(Intent intent, @Nullable Bundle options) {
    if (options != null) {
        startActivityForResult(intent, -1, options);
    } else {
        // Note we want to go through this call for compatibility with
        // applications that may have overridden the method.
        startActivityForResult(intent, -1);
    }
}

这里分别根据是否具有 options 调用到了 startActivityForResult(intent, requestCode, options)startActivityForResult(intent, requestCode),后者实际上也是转调到了前者,options 为 null。

public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
        @Nullable Bundle options) {
    if (mParent == null) {
        options = transferSpringboardActivityOptions(options);
        // 转调mInstrumentation.execStartActivity跳转Activity获取返回值ActivityResult
        Instrumentation.ActivityResult ar =
            mInstrumentation.execStartActivity(
                this, mMainThread.getApplicationThread(), mToken, this,
                intent, requestCode, options);
        if (ar != null) {
                // 通过 mMainThread.sendActivityResult发送Activity的Result
            mMainThread.sendActivityResult(
                mToken, mEmbeddedID, requestCode, ar.getResultCode(),
                ar.getResultData());
        }
        if (requestCode >= 0) {
            // 如果这个Activity启动需要下一个Activity的结果
            // 则会在下一个Activity的结果获得之前使得这个Activity不可见。
            mStartedActivity = true;
        }
        cancelInputsAndStartExitTransition(options);
        // TODO Consider clearing/flushing other event sources and events for child windows.
    } else {
            // 如果该Activity是一个子Activity,则会调用父Activity的startActivityFromChild启动Activity
        if (options != null) {
            mParent.startActivityFromChild(this, intent, requestCode, options);
        } else {
            // Note we want to go through this method for compatibility with
            // existing applications that may have overridden it.
            mParent.startActivityFromChild(this, intent, requestCode);
        }
    }
}

分为以下几步:

  1. 如果该 Activity 不是子 Activity,则直接调用 Instrumentation.execStartActivity 启动 Activity 并获取 ActivityResult
  2. ActivityResult 不为 null,则会通过 mMainThread.sendActivityResult 发送请求结果。
  3. 如果这个 Activity 的启动需要下个 Activity 设置的结果,那么会将 mStartedActivity 置为 true,从而使得在结果返回之前,该 Activity 不可见。
  4. 如果该 Activity 为一个子 Activity,调用父 ActivitystartActivityFromChild 方法进行 Activity 的启动。

我们看看 Activity.startActivityFromChild 的实现:

public void startActivityFromChild(@NonNull Activity child, @RequiresPermission Intent intent,
        int requestCode, @Nullable Bundle options) {
    options = transferSpringboardActivityOptions(options);
    Instrumentation.ActivityResult ar =
        mInstrumentation.execStartActivity(
            this, mMainThread.getApplicationThread(), mToken, child,
            intent, requestCode, options);
    if (ar != null) {
        mMainThread.sendActivityResult(
            mToken, child.mEmbeddedID, requestCode,
            ar.getResultCode(), ar.getResultData());
    }
    cancelInputsAndStartExitTransition(options);
}

它与 startActivityForResult 的逻辑类似,就是通过 Instrumentation.execStartActivity 启动 Activity 并获取 ActivityResult,不过它的第一个参数一个是调用的 Activity,一个是父 Activity 而已。同时,它没有了将 mStartedActivity 置为 true 的步骤,不会将 Activity 设置为不可见。可以看出来,Activity 的启动最后还是到了Instrumentation.execStartActivity 中:

public ActivityResult execStartActivity(
        Context who, IBinder contextThread, IBinder token, Activity target,
        Intent intent, int requestCode, Bundle options) {
    IApplicationThread whoThread = (IApplicationThread) contextThread;
    Uri referrer = target != null ? target.onProvideReferrer() : null;
    if (referrer != null) {
        intent.putExtra(Intent.EXTRA_REFERRER, referrer);
    }
    // 如果有设置 ActivityMonitor
    if (mActivityMonitors != null) {
        synchronized (mSync) {
                        // 遍历Monitory列表,调用 onStartActivity 回调
            final int N = mActivityMonitors.size();
            for (int i=0; i<N; i++) {
                final ActivityMonitor am = mActivityMonitors.get(i);
                ActivityResult result = null;
                if (am.ignoreMatchingSpecificIntents()) {
                    result = am.onStartActivity(intent);
                }
                // 如果 ActivityMonitor 对本次启动匹配,并且 Monitor 为 Blocking 的,则直接返回其结果
                if (result != null) {
                    am.mHits++;
                    return result;
                } else if (am.match(who, null, intent)) {
                    am.mHits++;
                    if (am.isBlocking()) {
                        return requestCode >= 0 ? am.getResult() : null;
                    }
                    break;
                }
            }
        }
    }
    try {
            // 通过 ActivityManager.getService() 获取 AMS 并调用其 startActivity
        intent.migrateExtraStreamToClipData();
        intent.prepareToLeaveProcess(who);
        int result = ActivityManager.getService()
            .startActivity(whoThread, who.getBasePackageName(), intent,
                    intent.resolveTypeIfNeeded(who.getContentResolver()),
                    token, target != null ? target.mEmbeddedID : null,
                    requestCode, 0, null, options);
        checkStartActivityResult(result, intent);
    } catch (RemoteException e) {
        throw new RuntimeException("Failure from system", e);
    }
    return null;
}

这里首先对 ActivityMonitor 进行了处理,如果传递进来了一个 activityMonitors 列表,则遍历它并调用其 onStartActvitiy 回调。之后,如果回调返回了结果或 ActivityMonitor 对这次启动的 match 返回了 true 且它是 Blocking 的,则直接将获取到的结果进行返回。

之后,通过 ActivityManager 这个本地代理的包装类获取到了 ActivityManagerService 的本地代理,并调用其 startActivity 方法。

我们先看看 ActivityManagerService 的本地代理是如何获取到的:

public static IActivityManager getService() {
    return IActivityManagerSingleton.get();
}
private static final Singleton<IActivityManager> IActivityManagerSingleton =
        new Singleton<IActivityManager>() {
            @Override
            protected IActivityManager create() {
                final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
                final IActivityManager am = IActivityManager.Stub.asInterface(b);
                return am;
            }
        };

它实际上是通过 IActivityManagerSingleton 这个单例,首先通过 ServiceManager 获取到了 AMSIBinder 对象,并通过 IActivityManager.Stub.asInterface 获取到了 AMS 的本地代理 Binder

服务端

AMS 进行权限校验

通过调用 AMSstartActivity 方法,来到了 SystemServer 进程,也就是服务端:

@Override
public final int startActivity(IApplicationThread caller, String callingPackage,
        Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
        int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
    return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
            resultWho, requestCode, startFlags, profilerInfo, bOptions,
            UserHandle.getCallingUserId());
}

它转调了 startActivityAsUser

public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
        Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
        int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
        boolean validateIncomingUser) {
    enforceNotIsolatedCaller("startActivity");
    userId = mActivityStartController.checkTargetUser(userId, validateIncomingUser,
            Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
    // 通过 ActivityStartController 的 obtainStarter 获取到了一个 ActivityStarter
    // 之后通过 Builder 的方式对参数设置后,通过 execute 方法进行执行
    return mActivityStartController.obtainStarter(intent, "startActivityAsUser")
            .setCaller(caller)
            .setCallingPackage(callingPackage)
            .setResolvedType(resolvedType)
            .setResultTo(resultTo)
            .setResultWho(resultWho)
            .setRequestCode(requestCode)
            .setStartFlags(startFlags)
            .setProfilerInfo(profilerInfo)
            .setActivityOptions(bOptions)
            .setMayWait(userId)
            .execute();
}

交给 ActivityStarter 处理 Activity 启动

这里通过工厂获取到了一个 ActivityStarter 对象,进行参数设置后将其返回。其 execute 方法如下:

ActivityStarter obtainStarter(Intent intent, String reason) {
    return mFactory.obtain().setIntent(intent).setReason(reason);
}

这里通过工厂获取到了一个 ActivityStarter 对象,进行参数设置后将其返回。其 execute 方法如下:

int execute() {
    try {
        // TODO(b/64750076): Look into passing request directly to these methods to allow
        // for transactional diffs and preprocessing.
        if (mRequest.mayWait) {
            return startActivityMayWait(mRequest.caller, mRequest.callingUid,
                    mRequest.callingPackage, mRequest.realCallingPid, mRequest.realCallingUid,
                    mRequest.intent, mRequest.resolvedType,
                    mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
                    mRequest.resultWho, mRequest.requestCode, mRequest.startFlags,
                    mRequest.profilerInfo, mRequest.waitResult, mRequest.globalConfig,
                    mRequest.activityOptions, mRequest.ignoreTargetSecurity, mRequest.userId,
                    mRequest.inTask, mRequest.reason,
                    mRequest.allowPendingRemoteAnimationRegistryLookup);
        } else {
            return startActivity(mRequest.caller, mRequest.intent, mRequest.ephemeralIntent,
                    mRequest.resolvedType, mRequest.activityInfo, mRequest.resolveInfo,
                    mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
                    mRequest.resultWho, mRequest.requestCode, mRequest.callingPid,
                    mRequest.callingUid, mRequest.callingPackage, mRequest.realCallingPid,
                    mRequest.realCallingUid, mRequest.startFlags, mRequest.activityOptions,
                    mRequest.ignoreTargetSecurity, mRequest.componentSpecified,
                    mRequest.outActivity, mRequest.inTask, mRequest.reason,
                    mRequest.allowPendingRemoteAnimationRegistryLookup);
        }
    } finally {
        onExecutionComplete();
    }
}

对 Intent 的解析(通过 PMS)

由于 mayWait 进行了设置,因此会调用到 startActivityMayWait 方法:

private int startActivityMayWait(IApplicationThread caller, int callingUid,
        String callingPackage, int requestRealCallingPid, int requestRealCallingUid,
        Intent intent, String resolvedType,
        IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
        IBinder resultTo, String resultWho, int requestCode, int startFlags,
        ProfilerInfo profilerInfo, WaitResult outResult,
        Configuration globalConfig, SafeActivityOptions options, boolean ignoreTargetSecurity,
        int userId, TaskRecord inTask, String reason,
        boolean allowPendingRemoteAnimationRegistryLookup) {
    // ...
    // Save a copy in case ephemeral needs it
    final Intent ephemeralIntent = new Intent(intent);
    // Don't modify the client's object!
    intent = new Intent(intent);
    // ...
    // 通过 mSupervisor.resolveIntent 进行 Intent 的解析
    ResolveInfo rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId,
            0 /* matchFlags */,
                    computeResolveFilterUid(
                            callingUid, realCallingUid, mRequest.filterCallingUid));
    // ...
    // 通过 mSupervisor.resolveActivity 进行 target 的解析,获取 ActivityInfo
    ActivityInfo aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, profilerInfo);
    synchronized (mService) {
        // 记录 Activiy 的信息
        final ActivityRecord[] outRecord = new ActivityRecord[1];
        // 调用 startActivity 启动 Activity
        int res = startActivity(caller, intent, ephemeralIntent, resolvedType, aInfo, rInfo,
                voiceSession, voiceInteractor, resultTo, resultWho, requestCode, callingPid,
                callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, options,
                ignoreTargetSecurity, componentSpecified, outRecord, inTask, reason,
                allowPendingRemoteAnimationRegistryLookup);
        mSupervisor.getActivityMetricsLogger().notifyActivityLaunched(res, outRecord[0]);
        return res;
    }
}

可以发现,这里有一个非常重要的类 mSupervisor,它负责了对 Intent 信息的解析以及对 Intent 中目标 Activity 的解析,最后通过了 ActivityStarterstartActivity 方法进行了 Activity 的启动。

这里的 mSupervisor 实际上是 ActivityStackSupervisor,我们通过它的 resolveIntent 方法对 Intent 进行了解析:

ResolveInfo resolveIntent(Intent intent, String resolvedType, int userId, int flags,
        int filterCallingUid) {
    synchronized (mService) {
        try {
            Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "resolveIntent");
            int modifiedFlags = flags
                    | PackageManager.MATCH_DEFAULT_ONLY | ActivityManagerService.STOCK_PM_FLAGS;
            if (intent.isWebIntent()
                        || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) != 0) {
                modifiedFlags |= PackageManager.MATCH_INSTANT;
            }
            // 通过 AMS.getPackageManagerINternalLocked 获取到了 PMS,并让 PMS 进行 Intent 的解析
            final long token = Binder.clearCallingIdentity();
            try {
                return mService.getPackageManagerInternalLocked().resolveIntent(
                        intent, resolvedType, modifiedFlags, userId, true, filterCallingUid);
            } finally {
                Binder.restoreCallingIdentity(token);
            }
        } finally {
            Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
        }
    }
}

这里实际上是通过 AMS.getPackageManagerInternalLocked 获取到了 PMS 并将 Intent 交给它解析。

ActivityInfo resolveActivity(Intent intent, ResolveInfo rInfo, int startFlags,
        ProfilerInfo profilerInfo) {
    final ActivityInfo aInfo = rInfo != null ? rInfo.activityInfo : null;
    if (aInfo != null) {
        // 获取解析出来的 packageName 以及 Activity 的 name
        intent.setComponent(new ComponentName(
                aInfo.applicationInfo.packageName, aInfo.name));
        // Don't debug things in the system process
        if (!aInfo.processName.equals("system")) {
            if ((startFlags & ActivityManager.START_FLAG_DEBUG) != 0) {
                mService.setDebugApp(aInfo.processName, true, false);
            }
            if ((startFlags & ActivityManager.START_FLAG_NATIVE_DEBUGGING) != 0) {
                mService.setNativeDebuggingAppLocked(aInfo.applicationInfo, aInfo.processName);
            }
            if ((startFlags & ActivityManager.START_FLAG_TRACK_ALLOCATION) != 0) {
                mService.setTrackAllocationApp(aInfo.applicationInfo, aInfo.processName);
            }
            if (profilerInfo != null) {
                mService.setProfileApp(aInfo.applicationInfo, aInfo.processName, profilerInfo);
            }
        }
        final String intentLaunchToken = intent.getLaunchToken();
        if (aInfo.launchToken == null && intentLaunchToken != null) {
            aInfo.launchToken = intentLaunchToken;
        }
    }
    return aInfo;
}

resolveActivity 则是通过 PMS 解析返回的 ResolveInfo 中解析出的 packageName 以及 Activity 的 name 构建出了一个 ComponentName 对象并设置给了 Intent

最后我们看到 ActivityStarter.startActivity 做了什么:

private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
            ActivityRecord[] outActivity) {
    int result = START_CANCELED;
    try {
            // 暂停 WMS 的布局
        mService.mWindowManager.deferSurfaceLayout();
        // 转调到 startActivityUnchecked
        result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
                startFlags, doResume, options, inTask, outActivity);
    } finally {
        // 如果 Activity 启动失败,通过 ActivityStack 将其关闭
        final ActivityStack stack = mStartActivity.getStack();
        if (!ActivityManager.isStartResultSuccessful(result) && stack != null) {
            stack.finishActivityLocked(mStartActivity, RESULT_CANCELED,
                    null /* intentResultData */, "startActivity", true /* oomAdj */);
        }
        // 继续 WMS 的布局
        mService.mWindowManager.continueSurfaceLayout();
    }
    postStartActivityProcessing(r, result, mTargetStack);
    return result;
}

这里首先暂停了 WMS 的布局,之后转调到了 startActivityUnchecked,之后继续 WMS 的布局。如果 Activity 启动失败,会通过 ActivityStack 将这个 Activity finish 掉。

处理启动 Flags

下面的 startActivityUnchecked 方法就是真正实现了对启动的 Flag 以及启动模式进行处理的地方了,让我们看看:

    private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
            ActivityRecord[] outActivity) {
        // 设置初始状态
        setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession,
                voiceInteractor);
        // 通过 Activity 的 Flag 对启动模式进行处理
        computeLaunchingTaskFlags();
        // 计算 SourceStack
        computeSourceStack();   

        // ...
        // 根据启动模式对是否开辟一个新的 Task 进行判断
        int result = START_SUCCESS;
        if (mStartActivity.resultTo == null && mInTask == null && !mAddingToTask
                && (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) {
            // 创建新的 TaskRecord
            newTask = true;
            result = setTaskFromReuseOrCreateNewTask(taskToAffiliate, topStack);
        } else if (mSourceRecord != null) {
            result = setTaskFromSourceRecord();
        } else if (mInTask != null) {
            result = setTaskFromInTask();
        } else {
            setTaskToCurrentTopOrCreateNewTask();
        }
        // ...
        // 调用 mTargetStack.startActivityLocked,这里会根据 Activity 启动模式判断是插入已存在的栈顶还是开新栈
        mTargetStack.startActivityLocked(mStartActivity, topFocused, newTask, mKeepCurTransition,
                mOptions);
        if (mDoResume) {
            final ActivityRecord topTaskActivity =
                    mStartActivity.getTask().topRunningActivityLocked();
            if (!mTargetStack.isFocusable()
                    || (topTaskActivity != null && topTaskActivity.mTaskOverlay
                    && mStartActivity != topTaskActivity)) {
                // 如果当前的 Stack 不是 focusable 的,则只是确保了 Activity 可见
                mTargetStack.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
                // ...
            } else {
                // 如果是 focusable,基本上都是走这里,调用 mSupervisor.resumeFocusedStackTopActivityLocked 方法
                if (mTargetStack.isFocusable() && !mSupervisor.isFocusedStack(mTargetStack)) {
                    mTargetStack.moveToFront("startActivityUnchecked");
                }
                mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,
                        mOptions);
            }
        } else if (mStartActivity != null) {
            mSupervisor.mRecentTasks.add(mStartActivity.getTask());
        }
        // ...
        return START_SUCCESS;
    }

这里首先根据 Activity 的 Flags 对启动模式进行了处理,主要是判断是否需要将 mLaunchFlags 中加入 FLAG_NEW_ACTIVITY_TASK ,之后对 SourceStack 进行了计算。

之后根据 mLaunchFlags 及一些相关的信息判断了是否需要创建一个新的 TaskRecord,若需要则 newTask 为 true。

之后调用了 mTargetStack.startActivityLocked,它会根据 Activity 的启动模式判断是插入栈顶还是开辟新栈。

真正启动 Activity

最后,不论如何启动,实际上都会调用到 mSupervisor.resumeFocusedStackTopActivityLocked

boolean resumeFocusedStackTopActivityLocked(
        ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
    if (!readyToResume()) {
        return false;
    }
    if (targetStack != null && isFocusedStack(targetStack)) {
        return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
    }
    final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
    if (r == null || !r.isState(RESUMED)) {
        mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
    } else if (r.isState(RESUMED)) {
        // Kick off any lingering app transitions form the MoveTaskToFront operation.
        mFocusedStack.executeAppTransition(targetOptions);
    }
    return false;
}

可以发现,最终都转调到了 ActivityStack.resumeTopActivityUncheckedLocked

boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
    if (mStackSupervisor.inResumeTopActivity) {
        return false;
    }
    boolean result = false;
    try {
        mStackSupervisor.inResumeTopActivity = true;
        // 调用 resumeTopActivityInnerLocked
        result = resumeTopActivityInnerLocked(prev, options);
        final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);
        if (next == null || !next.canTurnScreenOn()) {
            checkReadyForSleep();
        }
    } finally {
        mStackSupervisor.inResumeTopActivity = false;
    }
    return result;
}

这里转调到了 resumeTopActivityInnerLockedprev 实际上就是我们的 mStartActivity,也就是发起启动的 Activity

private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
    if (!mService.mBooting && !mService.mBooted) {
        // Not ready yet!
        return false;
    }

    // 获取要启动的 Activity
    final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);

        // ...

    // 转调到了 mStackSupervisor.startSpecificActivityLocked
    mStackSupervisor.startSpecificActivityLocked(next, true, false);
    // ...
}

这里代码很长很长,核心逻辑就是获取到了当前要启动的 Activity,然后调用了 mStackSupervisor.startSpecificActivityLocked 指定 Activity 启动。

void startSpecificActivityLocked(ActivityRecord r,
        boolean andResume, boolean checkConfig) {
    // Activity 启动的进程
    ProcessRecord app = mService.getProcessRecordLocked(r.processName,
            r.info.applicationInfo.uid, true);
    getLaunchTimeTracker().setLaunchTime(r);
    if (app != null && app.thread != null) {
        try {
            // ...
            // 调用 realStartActivityLocked
            realStartActivityLocked(r, app, andResume, checkConfig);
            return;
        } catch (RemoteException e) {
            Slog.w(TAG, "Exception when starting activity "
                    + r.intent.getComponent().flattenToShortString(), e);
        }
        // If a dead object exception was thrown -- fall through to
        // restart the application.
    }
    // 如果进程还未创建,则创建对应进程
    mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
            "activity", r.intent.getComponent(), false, false, true);
}

通过事务启动 Activity

首先获取到了 Activity 要启动的进程,之后调用到了 realStartActivityLocked 并将该进程传入:

final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
        boolean andResume, boolean checkConfig) throws RemoteException {

    // ...

        // 获取一个 ClientTranscation 事务
      final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
                    r.appToken);
        // 为事务添加一个 Callback,这个 Callback 通过 LaunchActivityItem.obtain 创建
    clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
            System.identityHashCode(r), r.info,
            // TODO: Have this take the merged configuration instead of separate global
            // and override configs.
            mergedConfiguration.getGlobalConfiguration(),
            mergedConfiguration.getOverrideConfiguration(), r.compat,
            r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
            r.persistentState, results, newIntents, mService.isNextTransitionForward(),
            profilerInfo));

    // 根据 andResume 与否获取对应的 ActivityLifecycleItem
    final ActivityLifecycleItem lifecycleItem;
    if (andResume) {
        lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
    } else {
        lifecycleItem = PauseActivityItem.obtain();
    }
    // 设置目标生命周期
    clientTransaction.setLifecycleStateRequest(lifecycleItem);

    // 获取 LifecycleManager,通过 scheduleTransaction 执行事务
    mService.getLifecycleManager().scheduleTransaction(clientTransaction);

    //...
}

这里首先获取了一个 ClientTranscation 事务,之后给它添加了一个 LaunchActivityItem 这个 Callback

之后根据 andResume 与否获取对应的 ActivityLifecycleItem

之后为 ClientTransaction 设置了 LifecycleStateRequest,默认情况下 andResume 均为 true,也就是 ResumeActivityItem,否则它是 PauseActivityItem,这个代表了目标状态。

最后获取 LifecycleManager,通过这个 ClientLifecycleMananger.scheduleTransaction 对事务进行执行。

根据 重学Android——基于Android9.0的Activity启动流程 这篇文章所说,这里就是 Android 9.0 与 8.0 的区别了,在 8.0 中是直接通过 app.thread.scheduleLaunchActivity 从而执行 Activity 的启动。而 9.0 中则是构造了一个 ClientTransaction,并通过 ClientLifecycleManager 进行事务的执行。

ClientLifecycleManager 中会调用 transaction.schedule,而在 ClientTransaction 中则会通过 mClient.schedule 对自己进行执行。而这个 mClient 则是 app.thread,也就是 ActivityThread 的内部类 ApplicationThread 的一个服务端代理 Binder

客户端

调用事务 Callback

通过 ApplicationThread,从而又回到了启动 Activity 的进程。

Application.scheduleTransaction 的实现如下:

@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
    ActivityThread.this.scheduleTransaction(transaction);
}

它会调用 ActivityThreadscheduleTransaction 方法,该方法在其父类 ClientTransactionHandler 中实现:

void scheduleTransaction(ClientTransaction transaction) {
    transaction.preExecute(this);
    sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}

它首先会调用到 transaction.preExecute,而 transaction 又会调用它的所有 CallbackpreExecute 方法进行预处理。

之后通过 ActivityThread 内部的 Handler 发送了 EXECUTE_TRANSACTION 消息:

public void handleMessage(Message msg) {
    switch(msg.what) {
            // ...
        case EXECUTE_TRANSACTION:
                final ClientTransaction transaction = (ClientTransaction) msg.obj;
                // 通过 mTransactionExecutor 对 transaction 进行了执行
                mTransactionExecutor.execute(transaction);
                if (isSystem()) {
                    transaction.recycle();
                }
                break;
            // ...
}

这里通过 mTransactionExecutor.executetransaction 进行了执行:

public void execute(ClientTransaction transaction) {
    final IBinder token = transaction.getActivityToken();
    log("Start resolving transaction for client: " + mTransactionHandler + ", token: " + token);

    executeCallbacks(transaction);

    executeLifecycleState(transaction);
    mPendingActions.clear();
    log("End resolving transaction");
}

在这个方法中,会首先调用 executeCallbacks 对传入的 Callback 进行执行(LaunchActivityItem

之后通过 executeLifecycleState 对设置的 LifecycleStateRequest 进行执行(PauseActivityItemResumeActivityItem)。

这里实际上就是在遍历 CallbackClientTransactionItem 并调用其 executepostExecute

调用 Callbacks

public void executeCallbacks(ClientTransaction transaction) {
    final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
    // 获取 AcitivityToken
    final IBinder token = transaction.getActivityToken();
    ActivityClientRecord r = mTransactionHandler.getActivityClient(token);

        // 遍历 Callback 获取 Item 并调用其 execute 及 postExecute 方法
    final int size = callbacks.size();
    for (int i = 0; i < size; ++i) {
        final ClientTransactionItem item = callbacks.get(i);
        // ...
        item.execute(mTransactionHandler, token, mPendingActions);
        item.postExecute(mTransactionHandler, token, mPendingActions);
        // ...
    }
}

执行 executeCallbacks 时,它会遍历 ClientTransactionItem 并执行。

LaunchActivityItem

由于我们之前传入的 ClientTransactionItemLaunchActivityItem,因此会调用到它的 execute 方法:

@Override
public void execute(ClientTransactionHandler client, IBinder token,
        PendingTransactionActions pendingActions) {
    Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
    ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
            mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
            mPendingResults, mPendingNewIntents, mIsForward,
            mProfilerInfo, client);
        // 调用了 client 的 handleLaunchActivity
    client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
    Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}

这里构造了一个 ActivityClientRecord,并调用了传递进来的 mTransactionHandlerhandleLaunchActivity 方法。这里的 mTransactionHandler 实际上是 ActivityThread 自身:

@Override
public Activity handleLaunchActivity(ActivityClientRecord r,
        PendingTransactionActions pendingActions, Intent customIntent) {
    // ...
    WindowManagerGlobal.initialize();
    // 调用 performLaunchActivity
    final Activity a = performLaunchActivity(r, customIntent);
    if (a != null) {
        // onRestoreInstanceState 的实现,将之前的 state 传入
        r.createdConfig = new Configuration(mConfiguration);
        reportSizeConfigurations(r);
        if (!r.activity.mFinished && pendingActions != null) {
            pendingActions.setOldState(r.state);
            pendingActions.setRestoreInstanceState(true);
            pendingActions.setCallOnPostCreate(true);
        }
    } else {
        // If there was an error, for any reason, tell the activity manager to stop us.
        try {
            ActivityManager.getService()
                    .finishActivity(r.token, Activity.RESULT_CANCELED, null,
                            Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
    }

    return a;
}

这里调用到了 performLaunchActivity,并且启动成功后会对 onRestoreInstanceState 的 state 进行设置:

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    // 获取 ActivityInfo
    ActivityInfo aInfo = r.activityInfo;
    if (r.packageInfo == null) {
        // 获取 packageInfo
        r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
                Context.CONTEXT_INCLUDE_CODE);
    }

        // 获取之前 PMS 解析出来的 ComponentName
    ComponentName component = r.intent.getComponent();
    // ...

    // 创建 Activity 所用的 ContextImpl
    ContextImpl appContext = createBaseContextForActivity(r);
    Activity activity = null;
    try {
        // 通过 mInstrumentation.newActivity 创建 Activity 实例
        java.lang.ClassLoader cl = appContext.getClassLoader();
        activity = mInstrumentation.newActivity(
                cl, component.getClassName(), r.intent);
        // ...
    } catch {
            // ...
    }

    try {
        // 调用 makeApplication 创建 Application,若已经存在会返回已存在的 Application
        Application app = r.packageInfo.makeApplication(false, mInstrumentation);

        // ...
        if (activity != null) {
            // 调用 Activity.attach
            activity.attach(appContext, this, getInstrumentation(), r.token,
                    r.ident, app, r.intent, r.activityInfo, title, r.parent,
                    r.embeddedID, r.lastNonConfigurationInstances, config,
                    r.referrer, r.voiceInteractor, window, r.configCallback);

            // ...
            // 通过 mInstrumentation.callActivityOnCreate 调用 Activity 的 onCreate 方法
            if (r.isPersistable()) {
                mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
            } else {
                mInstrumentation.callActivityOnCreate(activity, r.state);
            }
            ...
        }
        // 设置 ActivityClientRecord 的状态为 ON_CREATE
        r.setState(ON_CREATE);

                // 在 Activity 的容器中加入该 Activity
        mActivities.put(r.token, r);

    }
    // ...
    return activity;
}

可以看到,这里主要分为了以下几步:

  1. 获取 ActivityInfopackageInfo 以及之前通过 PMS 解析的 ComponentName
  2. 创建 Activity 需要的 ContextImpl
  3. 通过 mInstrumentation.newActivity 创建 Activity 实例。
  4. 调用 makeApplication 方法创建 Application,若已存在会返回已存在的 Application
  5. 调用 Activity.attach 方法对 Activity 进行初始化。
  6. 通过 mInstrumentation.callActivityOnCreate 方法调用 ActivityonCreate 方法。
  7. 设置 ActivityClientRecord 的状态为 ON_CREATE 并将其放入 ActvityThread 所存放 Activity 的容器中。
创建 Activity 实例

我们先看看 Activity 对象是如何被创建出来的:

public Activity newActivity(ClassLoader cl, String className,
        Intent intent)
        throws InstantiationException, IllegalAccessException,
        ClassNotFoundException {
    String pkg = intent != null && intent.getComponent() != null
            ? intent.getComponent().getPackageName() : null;
    return getFactory(pkg).instantiateActivity(cl, className, intent);
}

这里获取到的 Factory 实际上是 AppComponentFactory,其 instantiateActivity 如下:

public @NonNull Activity instantiateActivity(@NonNull ClassLoader cl, @NonNull String className,
        @Nullable Intent intent)
        throws InstantiationException, IllegalAccessException, ClassNotFoundException {
    return (Activity) cl.loadClass(className).newInstance();
}

可以看到,这里实际上是通过反射构建的 Activity 对应的实例,它的 Class 对象通过之前传入的 ClassLoader 加载。

Activity.attach
final void attach(Context context, ActivityThread aThread,
        Instrumentation instr, IBinder token, int ident,
        Application application, Intent intent, ActivityInfo info,
        CharSequence title, Activity parent, String id,
        NonConfigurationInstances lastNonConfigurationInstances,
        Configuration config, String referrer, IVoiceInteractor voiceInteractor,
        Window window, ActivityConfigCallback activityConfigCallback) {
    // 将 context attach 到 Activity
    attachBaseContext(context);
    mFragments.attachHost(null /*parent*/);
    // 创建 PhoneWindow
    mWindow = new PhoneWindow(this, window, activityConfigCallback);
    // ...
    // 为 PhoneWindow 设置 WindowManager
    mWindow.setWindowManager(
            (WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
            mToken, mComponent.flattenToString(),
            (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
    if (mParent != null) {
        mWindow.setContainer(mParent.getWindow());
    }
    mWindowManager = mWindow.getWindowManager();
    mCurrentConfig = config;
    mWindow.setColorMode(info.colorMode);
}

这里主要是为 Activity attach 之前创建的 ContextImpl,并创建 PhoneWindow以及一些初始化操作,创建 PhoneWindow 时就会对 DecorView 进行创建。

Activity onCreate 的调用

通过 mInstrumentation.callActivityOnCreate 可以对 ActivityonCreate 方法进行调用:

public void callActivityOnCreate(Activity activity, Bundle icicle) {
    prePerformCreate(activity);
    activity.performCreate(icicle);    
    postPerformCreate(activity);
}

可以发现,它调用到了 Activity.performCreate

final void performCreate(Bundle icicle, PersistableBundle persistentState) {
    mCanEnterPictureInPicture = true;
    restoreHasCurrentPermissionRequest(icicle);
    if (persistentState != null) {
        onCreate(icicle, persistentState);
    } else {
        onCreate(icicle);
    }
    mActivityTransitionState.readState(icicle);
    mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
            com.android.internal.R.styleable.Window_windowNoDisplay, false);
    mFragments.dispatchActivityCreated();
    mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
}

可以看到,这里调用到了 ActivityonCreate,并在之后调用到了 mFragments.dispatchActivityCreated,它之后会调用到 FragmentManager.dispatchActivityCreated

调用 LifecycleStateRequests

private void executeLifecycleState(ClientTransaction transaction) {
    final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
    if (lifecycleItem == null) {
        // No lifecycle request, return early.
        return;
    }
    // ...
    // 执行生命周期之前的状态
    cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */);

    // 切换状态
    lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
    lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
}

cycleToPath

调用 executeLifecycleState 时,首先会调用 cycleToPath 执行设置的生命周期之前的状态,之后会调用 lifecycleItem.execute 进行状态切换。

 private void cycleToPath(ActivityClientRecord r, int finish,
            boolean excludeLastState) {
    final int start = r.getLifecycleState();
    log("Cycle from: " + start + " to: " + finish + " excludeLastState:" + excludeLastState);
    final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
    performLifecycleSequence(r, path);
}

可以看到,这里首先根据 getLifecyclePath 方法获取到了一个生命周期的路径 path,之后调用了 performLifecycleSequeue 并传入 path 执行对应的生命周期。

public IntArray getLifecyclePath(int start, int finish, boolean excludeLastState) {
    ...
    if (finish >= start) {
        // 添加 start 到 finish 之间的生命周期
        for (int i = start + 1; i <= finish; i++) {
            mLifecycleSequence.add(i);
        }
    } 
    // ...
    // 移除最后的生命周期
    if (excludeLastState && mLifecycleSequence.size() != 0) {
        mLifecycleSequence.remove(mLifecycleSequence.size() - 1);
    }

    return mLifecycleSequence;
}

可以发现 getLifecyclePath 中会将从当前生命周期到目标生命周期之间的所有生命周期添加进数组,由于 excludeLastState 为 true,因此目标生命周期不会包含在其中。

之后我们看到 performLifecycleSequence

private void performLifecycleSequence(ActivityClientRecord r, IntArray path) {
    final int size = path.size();
    for (int i = 0, state; i < size; i++) {
        state = path.get(i);
        log("Transitioning to state: " + state);
        switch (state) {
            // ...
            case ON_START:
                mTransactionHandler.handleStartActivity(r, mPendingActions);
                break;
            // ...
        }
    }
}

它会由开始的生命周期开始,一个个遍历并调用对应的 handleXXXActivity 方法。

Activity.onStart 的调用

由于我们当前是 ON_CREATE 状态,因此会通过 mTransactionHandler(也就是 ActivityThread) 的 handleStartActivity 进行 ActivityonStart 的调用:

public void handleStartActivity(ActivityClientRecord r,
        PendingTransactionActions pendingActions) {
    // ...
    // 调用 onStart
    activity.performStart("handleStartActivity");
    r.setState(ON_START);
    // ...
}

由此,ActivityperformStart 被调用:

final void performStart() {
    mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
    mFragments.noteStateNotSaved();
    mCalled = false;
    mFragments.execPendingActions();
    // 通过 mInstrumentation 调用 onStart
    mInstrumentation.callActivityOnStart(this);
    if (!mCalled) {
        throw new SuperNotCalledException(
            "Activity " + mComponent.toShortString() +
            " did not call through to super.onStart()");
    }
    mFragments.dispatchStart();
    mFragments.reportLoaderStart();
    // ...
}

它实际上仍然会通过 mInstrumentation.callActivityOnStart 调用 ActivityonStart

public void callActivityOnStart(Activity activity) {
    activity.onStart();
}
Activity.onResume 的调用

接着会调用到 handleActivityOnResume 方法:

@Override
public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
        String reason) {

    // 调用 performResumeActivity
    final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
    // ...
    final Activity a = r.activity;
    // ...
    if (r.window == null && !a.mFinished && willBeVisible) {
            // DecorView 的获取
        r.window = r.activity.getWindow();
        View decor = r.window.getDecorView();
        decor.setVisibility(View.INVISIBLE);
        // 通过 Activity 获取 WindowMananger
        ViewManager wm = a.getWindowManager();
        WindowManager.LayoutParams l = r.window.getAttributes();
        a.mDecor = decor;
        if (a.mVisibleFromClient) {
            if (!a.mWindowAdded) {
                a.mWindowAdded = true;
                // 如果还未 addWindow,通过 WindowManager 进行 addWindow
                wm.addView(decor, l);
            } else {
                // ...
            }
        }
    }
    // ...
    Looper.myQueue().addIdleHandler(new Idler());
}

这里首先通过 performResumeActivity 调用 ActivityonResume,之后如果该 ActivityWindow 还没有添加,将 DecorView 通过 WindowManager 进行添加,这就是绘制的起点。

performResumeActivity 中:

public ActivityClientRecord performResumeActivity(IBinder token, boolean finalStateRequest,
        String reason) {
    final ActivityClientRecord r = mActivities.get(token);
    if (localLOGV) {
        Slog.v(TAG, "Performing resume of " + r + " finished=" + r.activity.mFinished);
    }
    if (r == null || r.activity.mFinished) {
        return null;
    }
    // ...
    try {
            // ..
        // 调用 Activity 的 performResume 方法
        r.activity.performResume(r.startsNotResumed, reason);
        r.state = null;
        r.persistentState = null;
        r.setState(ON_RESUME);
    } catch (Exception e) {
        if (!mInstrumentation.onException(r.activity, e)) {
            throw new RuntimeException("Unable to resume activity "
                    + r.intent.getComponent().toShortString() + ": " + e.toString(), e);
        }
    }
    return r;
}

可以看到,它会调用到 Activity.performResume 方法:

final void performResume() {
        // 首先调用了 performRestart
    performRestart();
    mFragments.execPendingActions();
    mLastNonConfigurationInstances = null;
    mCalled = false;
    // 通过 mInstrumentation.callActivityOnResume 调用 onResume
    mInstrumentation.callActivityOnResume(this);
    // ...
    mFragments.dispatchResume();
    mFragments.execPendingActions();
    onPostResume();
    // ...
}

这里首先调用了 performRestart,它会首先判断应用是不是从 stop 状态直接到达 onResume,如果是则会通过 mInstrumentation 调用 onRestartonStart

之后仍然是通过 mInstrumentation.callActivityOnResume 方法实现 onResume 的调用:

public void callActivityOnResume(Activity activity) {
    activity.mResumed = true;
    activity.onResume();

    if (mActivityMonitors != null) {
        synchronized (mSync) {
            final int N = mActivityMonitors.size();
            for (int i=0; i<N; i++) {
                final ActivityMonitor am = mActivityMonitors.get(i);
                am.match(activity, activity, activity.getIntent());
            }
        }
    }
}

由于启动 Activity 最多目标状态也就是到 PAUSE,因此到这里 cycleToPath 就不会继续往下执行了。

ResumeActivityItem

当目标状态为 Resume 时,会调用到 ResumeActivityItem.execute

@Override
public void execute(ClientTransactionHandler client, IBinder token,
        PendingTransactionActions pendingActions) {
    Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityResume");
    client.handleResumeActivity(token, true /* finalStateRequest */, mIsForward,
            "RESUME_ACTIVITY");
    Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}

它会调用到 ActivityThread.handleResumeActivity,之后就与上面的流程相同了,不再赘述。

PauseActivityItem

Activity.onPause 的调用

当目标状态为 PAUSE 时,则会调用到 PauseActivityItem.execute

@Override
public void execute(ClientTransactionHandler client, IBinder token,
        PendingTransactionActions pendingActions) {
    Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
    client.handlePauseActivity(token, mFinished, mUserLeaving, mConfigChanges, pendingActions,
            "PAUSE_ACTIVITY_ITEM");
    Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}

execute 方法看的出来,它同样也调用到了 ActivityThread.handlePauseActivity

@Override
public void handlePauseActivity(IBinder token, boolean finished, boolean userLeaving,
        int configChanges, PendingTransactionActions pendingActions, String reason) {
    ActivityClientRecord r = mActivities.get(token);
    if (r != null) {
        if (userLeaving) {
            performUserLeavingActivity(r);
        }
        r.activity.mConfigChangeFlags |= configChanges;
        performPauseActivity(r, finished, reason, pendingActions);
        // Make sure any pending writes are now committed.
        if (r.isPreHoneycomb()) {
            QueuedWork.waitToFinish();
        }
        mSomeActivitiesChanged = true;
    }
}

它会根据传递的 token 拿到对应的 ActivityClientRecord 对象,然后调用 performPauseActivity 方法:

private Bundle performPauseActivity(ActivityClientRecord r, boolean finished, String reason,
        PendingTransactionActions pendingActions) {
    // ...
    // 如果需要保存状态,调用 OnSaveInstanceState
    if (shouldSaveState) {
        callActivityOnSaveInstanceState(r);
    }
    // 调用 onPause
    performPauseActivityIfNeeded(r, reason);
    // ...
    return shouldSaveState ? r.state : null;
}

首先,在需要保存状态的情况下,会调用 callActivityOnSaveInstanceState 方法对 onSaveInstanceState 进行调用。

之后会调用 performPauseActivityIfNeeded 方法:

private void performPauseActivityIfNeeded(ActivityClientRecord r, String reason) {
    if (r.paused) {
        // You are already paused silly...
        return;
    }
    try {
        r.activity.mCalled = false;
        mInstrumentation.callActivityOnPause(r.activity);
        if (!r.activity.mCalled) {
            throw new SuperNotCalledException("Activity " + safeToComponentShortString(r.intent)
                    + " did not call through to super.onPause()");
        }
    } catch (SuperNotCalledException e) {
        throw e;
    } catch (Exception e) {
        if (!mInstrumentation.onException(r.activity, e)) {
            throw new RuntimeException("Unable to pause activity "
                    + safeToComponentShortString(r.intent) + ": " + e.toString(), e);
        }
    }
    r.setState(ON_PAUSE);
}

它会通过 mInstrumentation.callActivityOnPause 方法调用 ActivityonPause 方法:

public void callActivityOnPause(Activity activity) {
    activity.performPause();
}

调用到了 Activity.performPause 方法:

final void performPause() {
    mDoReportFullyDrawn = false;
    mFragments.dispatchPause();
    mCalled = false;
    onPause();
    mResumed = false;
    if (!mCalled && getApplicationInfo().targetSdkVersion
            >= android.os.Build.VERSION_CODES.GINGERBREAD) {
        throw new SuperNotCalledException(
                "Activity " + mComponent.toShortString() +
                " did not call through to super.onPause()");
    }
    mResumed = false;
}

在这个方法中,进行了 onPause 的调用。

总结

Activity 的启动流程可以大致归纳如下:

  1. 客户端(用户进程)
    1. Activity 通过 startActivity 最终会调用到 startActivityForResult 方法。
    2. startActivityForResult 中通过 mInstrumentation.execStartActivity 执行 Activity 的启动。
    3. Instrumentation 通过 ActivityManager 这个本地包装类获取到 AMS 的客户端 Binder
  2. 服务端(SystemServer 进程)
    1. AMS 通过 startActivityAsUser 进行权限的校验,之后通过 Builder 模式构建 ActivityStarter 并调用其 execute 方法。
    2. ActivityStarter 会通过 startActivityMayWait 方法,通过 mSupervisor 访问 PMS 进行 Intent 的解析并返回 ResolveResult 对象。
    3. 之后会通过 startActivityUnchecked 方法对 Activity 的启动模式进行处理,并与 ActivityStack 交互完成栈的管理。
    4. 之后会通过 ActivityStack.resumeFocusedStackTopActivityLocked 将启动任务交给 ActivityStack
    5. ActivityStack 最终会调用 realStartActivityLocked 构造一个 ClientTransaction 事务。
    6. 之后会向该 ClientTransaction 事务中添加 LaunchActivityItem 这一 Callback
    7. 之后会向 ClientTransaction 设置目标生命周期(ResumeActivityItemPauseActivityItem,默认情况下为 Resume)。
    8. 调用 ClientTransaction.schedule 之后,会通过 IApplicationThread 这一代理对象的 scheduleTransaction 回到客户端进程,并通过它来执行该事务。
  3. 客户端(用户进程)
    1. ApplicationThread 会转调到其外部类 ActivityThreadscheduleTransaction 方法。
    2. scheduleTransaction 方法会分别调用 executeCallbacksexecuteStateRequest 方法。
    3. executeCallbacks 会调用到 LaunchActivityItemexecute 方法,之后转调到 ActivityThreadhandleLaunchActivity 方法。
    4. handleLaunchActivity 方法会调用到 performLaunchActivity 方法:
      1. Activity 对应的 ContextImpl 进行创建
      2. 调用 Instrumentation.newActivity,它会根据 PMS 解析出的信息通过反射构建 Activity 实例
      3. 构建完成后通过 activity.attach 进行如对 activity 中的 Context 进行 attach、创建 PhoneWindowPhoneWindow 创建会创建 DecorView)、设置 WindowManager 等一系列初始化操作。
      4. 通过 Instrumentation.callActivityOnCreate 方法转调到 Activity.performCreate 方法从而调用 onCreate 方法。
    5. executeStateRequest 方法会分别调用 cycleToPath 方法以及 lifecycleItem.execute 方法。
    6. cycleToPath 会将从当前状态 ON_CREATE 到前面指定的目标生命周期(默认 RESUME)前的所有生命周期通过调用 ActivityThread.handleXXXActivity 实现对生命周期的调用。
      • 其中 onResume 的调用中会在 handleResumeActivity 调用时将 DecorView 添加到 WindowManagerwm.addView),这里就是绘制的起始点。
    7. lifecycleItem.execute 会将指定的目标生命周期(默认 RESUME)的 handleXXXActivity 方法进行调用,从而调用目标生命周期的回调函数。

可以发现,Activity 要启动一个 Activity 需要与 Instrumentation 进行交互,Instrumentation 就像是负责替 ActivityAMS 直接通信的秘书,当 Activity 想要启动另一个 Activity 时,它就会告诉 InstrumentationInstrumentation 就会将消息向 AMS 进行传递,AMS 会对要启动的相关信息进行核验,如果觉得没问题就会让 ActivityStarter 来负责这件启动 Activity 的任务。ActivityStarter 首先会找到 PMS 对这个启动任务的目标进行解析,确定目标以后又会交给 ActivtiyStack 对这个 ActivityStack 进行管理,ActivityStack 的处理结束之后,就会通过 ApplicationThread 来告知 ActivityThreadActivityThread 就像一个负责传达服务端发来的消息的邮局,它会将消息转发给 Instrumentation,而 Instrumentation 就会负责对新启动的 Activity 进行创建并调用其对应的生命周期。也就是说 Activity 只需要与 Instrumentation 进行交流就好。

参考资料

AOSP Reference

重学Android——基于Android9.0的Activity启动流程

Android之9.0Activity启动流程(二)

点赞

发表评论

电子邮件地址不会被公开。必填项已用 * 标注

%d 博主赞过: