Activity启动流程总结-生命周期

前言

对于Activity的启动流程,从事Android开发的同学都很熟悉。这里仅结合自己的理解,通过博文梳理和记录Activity启动流程关键节点,便于记忆和将来回顾。

官方Activity生命周期示意图:

activity-lifecycle

当 Activity A 启动 Activity B 时,它们各自的生命周期回调顺序是:

  1. Activity A 的 onPause() 方法执行。
  2. Activity B 的 onCreate()、onStart() 和 onResume() 方法依次执行。(Activity B 现在具有用户焦点。)
  3. 然后,如果 Activity A 在屏幕上不再可见,则其 onStop() 方法执行。

大家对于这样的结论都已熟知,但是ActivityManagerService是如何调度各Activity的生命回调,以及在什么时机调度等问题,就需要进入Activity的启动流程来找答案。

源码探究

文中源码基于Android 9.0

startActivity

首先通过activity.startActivity发起启动Activity的请求指令,startActivity最终调用Instrumentation的execStartActivity方法:

[Instrumentation.java]

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相关部分
    // ···
    try {
        intent.migrateExtraStreamToClipData();
        intent.prepareToLeaveProcess(who);
        // 获取IActivityManager binder通信接口,执行startActivity方法调用到AMS端
        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;
}

该方法中通过IActivityManager.startActivity方法将指令和参数传递给ActivityManagerService,触发ActivityManagerService对应的startActivity方法。

startActivityAsUser

ActivityManagerService的startActivity方法中又执行到startActivityAsUser方法:

[ActivityManagerService.java]

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");

    // 根据uid检查权限并返回修正后的uid
    userId = mActivityStartController.checkTargetUser(userId, validateIncomingUser,
            Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");

    // TODO: Switch to user app stacks here.
    // 获取ActivityStarter(用于配置和执行启动Activity),调用其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保存启动参数,然后执行启动,execute方法中将调用startActivityMayWait方法。

startActivityMayWait

[ActivityStarter.java]

private int startActivityMayWait(IApplicationThread caller, int callingUid,
        String callingPackage, 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) {
    // Refuse possible leaked file descriptors
    if (intent != null && intent.hasFileDescriptors()) {
        throw new IllegalArgumentException("File descriptors passed in Intent");
    }
    mSupervisor.getActivityMetricsLogger().notifyActivityLaunching();
    // 标记intent有明确设置接收的组件
    boolean componentSpecified = intent.getComponent() != null;

    final int realCallingPid = Binder.getCallingPid();
    final int realCallingUid = Binder.getCallingUid();

    int callingPid;
    if (callingUid >= 0) {
        callingPid = -1;
    } else if (caller == null) {
        callingPid = realCallingPid;
        callingUid = realCallingUid;
    } else {
        callingPid = callingUid = -1;
    }
    
    // 创建intent的副本
    // 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);
    // 省略拦截处理跳转InstantAPP安装相关部分 ···
    
    // 通过PackageManagerService查询该intent是否有匹配的ResolveInfo
    ResolveInfo rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId,
            0 /* matchFlags */,
                    computeResolveFilterUid(
                            callingUid, realCallingUid, mRequest.filterCallingUid));
    if (rInfo == null) {
        // 省略ResolveInfo未找到情况的处理部分
        // ···
    }
    // Collect information about the target of the Intent.
    // 获取ResolveInfo中的ActivityInfo
    ActivityInfo aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, profilerInfo);
    
    synchronized (mService) {
        // 获取处于焦点的ActivityStack
        final ActivityStack stack = mSupervisor.mFocusedStack;
        stack.mConfigWillChange = globalConfig != null
                && mService.getGlobalConfiguration().diff(globalConfig) != 0;
        if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION,
                "Starting activity when config will change = " + stack.mConfigWillChange);

        final long origId = Binder.clearCallingIdentity();
        
        // 省略heavy-weight进程处理部分 ···
        
        // 用来保存start Activity过程中创建或复用的ActivityRecord
        final ActivityRecord[] outRecord = new ActivityRecord[1];
        // 进一步执行启动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);

        Binder.restoreCallingIdentity(origId);
        
        // 省略更新Configuration部分 ···
        
        // 省略对启动结果outResult的处理部分,若存在需要等待目标Activity所在进程启动
        // 或等待特定Activity可见等情况,则将阻塞等待唤醒再返回结果。
        // ···
    }
}

该方法中对intent做了检查之后,调用startActivity方法进一步进行启动流程,其中又调用另一个startActivity重载方法:

[ActivityStarter.java]

private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
        String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
        IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
        IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
        String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
        SafeActivityOptions options,
        boolean ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[] outActivity,
        TaskRecord inTask, boolean allowPendingRemoteAnimationRegistryLookup) {
    // err记录运行结果,默认记为START_SUCCESS
    int err = ActivityManager.START_SUCCESS;
    // Pull the optional Ephemeral Installer-only bundle out of the options early.
    final Bundle verificationBundle
            = options != null ? options.popAppVerificationBundle() : null;
    
    // 调用端(即发起start请求的APP进程)对应的ProcessRecord
    ProcessRecord callerApp = null;
    if (caller != null) {
        // 从AMS中的缓存集合获取
        callerApp = mService.getRecordForAppLocked(caller);
        if (callerApp != null) {
            // 获取调用端pid、uid
            callingPid = callerApp.pid;
            callingUid = callerApp.info.uid;
        } else {
            // 正常情况下,APP进程都会在AMS有一个ProcessRecord。若无,则认为非法。
            Slog.w(TAG, "Unable to find app for caller " + caller
                    + " (pid=" + callingPid + ") when starting: "
                    + intent.toString());
            err = ActivityManager.START_PERMISSION_DENIED;
        }
    }
    
    // ActivityRecord对应表示Activity栈中的一个Activity
    // sourceRecord表示调用端Activity
    ActivityRecord sourceRecord = null;
    // resultRecord表示在onActivityResult接收结果的Activity
    ActivityRecord resultRecord = null;
    // resultTo表示调用端Activity的token,可通过它获取Activity对应的ActivityRecord
    if (resultTo != null) {
        sourceRecord = mSupervisor.isInAnyStackLocked(resultTo);
        if (DEBUG_RESULTS) Slog.v(TAG_RESULTS,
                "Will send result to " + resultTo + " " + sourceRecord);
        if (sourceRecord != null) {
            if (requestCode >= 0 && !sourceRecord.finishing) {
                // 当需要回调onActivityResult的情况下,即调用startActivityForResult方法
                // requestCode参数大于0,resultRecord即为sourceRecord
                resultRecord = sourceRecord;
            }
        }
    }
    
    // 获取intent中设置的启动标识
    final int launchFlags = intent.getFlags();

    if ((launchFlags & Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0 && sourceRecord != null) {
        // 省略处理FLAG_ACTIVITY_FORWARD_RESULT相关部分
        // ···
    }
    
    if (err == ActivityManager.START_SUCCESS && intent.getComponent() == null) {
        // We couldn't find a class that can handle the given Intent.
        // That's the end of that!
        err = ActivityManager.START_INTENT_NOT_RESOLVED;
    }

    if (err == ActivityManager.START_SUCCESS && aInfo == null) {
        // We couldn't find the specific class specified in the Intent.
        // Also the end of the line.
        err = ActivityManager.START_CLASS_NOT_FOUND;
    }
    
    // 省略检查语音会话时启动Activity部分,若目标Activity不支持VOICE类别,则标记
    // err = ActivityManager.START_NOT_VOICE_COMPATIBLE
    // ···
    
    final ActivityStack resultStack = resultRecord == null ? null : resultRecord.getStack();

    // 若err标记为失败,则终止启动
    if (err != START_SUCCESS) {
        if (resultRecord != null) {
            // 通知调用端onActivityResult,并传回RESULT_CANCELED
            resultStack.sendActivityResultLocked(
                    -1, resultRecord, resultWho, requestCode, RESULT_CANCELED, null);
        }
        SafeActivityOptions.abort(options);
        return err;
    }
    
    // 检查权限,若权限不通过则将abort标记为true
    boolean abort = !mSupervisor.checkStartAnyActivityPermission(intent, aInfo, resultWho,
            requestCode, callingPid, callingUid, callingPackage, ignoreTargetSecurity,
            inTask != null, callerApp, resultRecord, resultStack);
    abort |= !mService.mIntentFirewall.checkStartActivity(intent, callingUid,
            callingPid, resolvedType, aInfo.applicationInfo);
            
    // 省略动画选项设置相关部分 ···
    
    // 省略IActivityController部分,用于监听拦截Activity启动,可通过AMS.setActivityController
    // 设置监听器,若拦截将标记abort=true。
    // 省略ActivityStartInterceptor部分 ···
    
    // 判断是否终止
    if (abort) {
        if (resultRecord != null) {
            // 通知调用端onActivityResult,并传回RESULT_CANCELED
            resultStack.sendActivityResultLocked(-1, resultRecord, resultWho, requestCode,
                    RESULT_CANCELED, null);
        }
        // We pretend to the caller that it was really started, but
        // they will just get a cancel result.
        ActivityOptions.abort(checkedOptions);
        return START_ABORTED;
    }
    
    // 省略权限检查部分 ···
    // 省略临时安装APP部分 ···
    
    // 新建ActivityRecord,保存Activity启动相关参数
    ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid,
            callingPackage, intent, resolvedType, aInfo, mService.getGlobalConfiguration(),
            resultRecord, resultWho, requestCode, componentSpecified, voiceSession != null,
            mSupervisor, checkedOptions, sourceRecord);
    if (outActivity != null) {
        outActivity[0] = r;
    }
    
    // 省略赋值AppTimeTracker部分 ···
    // 省略检查是否允许应用切换部分 ···
    
    return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
            true /* doResume */, checkedOptions, inTask, outActivity);
}

该方法中对当前能否启动目标Activity进行了各项检查,并创建ActivityRecord用以保存Activity启动信息,其中还有涉及Activity启动拦截器的调用(若有设置)。最后调用了另一个重载方法startActivity,其中又调用startActivityUnchecked方法。

startActivityUnchecked

[ActivityStarter.java]

private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
        IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
        int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
        ActivityRecord[] outActivity) {

    // 初始化ActivityStarter的成员变量,用当前启动信息设置
    setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession,
            voiceInteractor);

    // 调整启动标识
    computeLaunchingTaskFlags();

    // 获取sourceRecord的ActivityStack,若调用端Activity即将finish,则修改启动标识
    computeSourceStack();
    
    // 设置调整后的启动标识
    mIntent.setFlags(mLaunchFlags);
    
    // 根据启动标识和启动模式检查是否新建TASK或加入现有TASK。若加入现有TASK,则返回该TASK中可重用的ActivityRecord。
    ActivityRecord reusedActivity = getReusableIntentActivity();
    
    // 省略窗口模式相关部分 ···
    
    if (reusedActivity != null) {
        // 省略设置ActivityRecord和对应TaskRecord,根据启动模式和启动标识清理任务栈,
        // 触发复用Activity的onNewIntent方法等等部分
        // ···
    }
    
    // 省略检查packageName部分 ···
    // 省略当目标Activity与当前顶部Activity一致时,根据启动标识和模式判断是否不启动新Activity以及对应的处理的相关部分
    
    // 省略设置TaskRecord部分
    
    // 省略权限设置
    // ···
    
    // 进行TaskRecord、APP Window Token、动画、窗口复用等相关检查和配置
    mTargetStack.startActivityLocked(mStartActivity, topFocused, newTask, mKeepCurTransition,
            mOptions);
    if (mDoResume) {
        final ActivityRecord topTaskActivity =
                mStartActivity.getTask().topRunningActivityLocked();
        if (!mTargetStack.isFocusable()
                || (topTaskActivity != null && topTaskActivity.mTaskOverlay
                && mStartActivity != topTaskActivity)) {
            // If the activity is not focusable, we can't resume it, but still would like to
            // make sure it becomes visible as it starts (this will also trigger entry
            // animation). An example of this are PIP activities.
            // Also, we don't want to resume activities in a task that currently has an overlay
            // as the starting activity just needs to be in the visible paused state until the
            // over is removed.
            mTargetStack.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
            // Go ahead and tell window manager to execute app transition for this activity
            // since the app transition will not be triggered through the resume channel.
            mService.mWindowManager.executeAppTransition();
        } else {
            // If the target stack was not previously focusable (previous top running activity
            // on that stack was not visible) then any prior calls to move the stack to the
            // will not update the focused stack.  If starting the new activity now allows the
            // task stack to be focusable, then ensure that we now update the focused stack
            // accordingly.
            if (mTargetStack.isFocusable() && !mSupervisor.isFocusedStack(mTargetStack)) {
                mTargetStack.moveToFront("startActivityUnchecked");
            }
            // resumeFocusedStackTopActivityLocked方法进一步执行启动操作
            mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,
                    mOptions);
        }
    } else if (mStartActivity != null) {
        // 加入最近任务列表
        mSupervisor.mRecentTasks.add(mStartActivity.getTask());
    }
    mSupervisor.updateUserStackLocked(mStartActivity.userId, mTargetStack);

    mSupervisor.handleNonResizableTaskIfNeeded(mStartActivity.getTask(), preferredWindowingMode,
            preferredLaunchDisplayId, mTargetStack);

    return START_SUCCESS;
}

该方法中会进行启动标识和启动模式检查,判断是否要复用的TaskRecord、ActivityRecord还是重新创建。若要新启动一个Activity,则调用ActivityStackSupervisor的resumeFocusedStackTopActivityLocked方法,继续进行启动流程。

resumeFocusedStackTopActivityLocked

[ActivityStackSupervisor.java]

boolean resumeFocusedStackTopActivityLocked(
        ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {

    if (!readyToResume()) {
        return false;
    }

    // 判断目标Activity栈是否处于焦点,是的话则调用其resumeTopActivityUncheckedLocked方法进一步进行启动流程
    if (targetStack != null && isFocusedStack(targetStack)) {
        return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
    }

    // ···

    return false;
}

该方法中主要对Activity栈的焦点进行检查,之后便通过ActivityStack的resumeTopActivityUncheckedLocked继续执行启动流程。

resumeTopActivityUncheckedLocked

[ActivityStack.java]

boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
    // inResumeTopActivity标记当前处于resumeTopActivity过程中,用于避免重复递归调用。
    if (mStackSupervisor.inResumeTopActivity) {
        // Don't even start recursing.
        return false;
    }

    boolean result = false;
    try {
        // Protect against recursion.
        mStackSupervisor.inResumeTopActivity = true;
        // Activity启动流程核心方法
        result = resumeTopActivityInnerLocked(prev, options);

        // When resuming the top activity, it may be necessary to pause the top activity (for
        // example, returning to the lock screen. We suppress the normal pause logic in
        // {@link #resumeTopActivityUncheckedLocked}, since the top activity is resumed at the
        // end. We call the {@link ActivityStackSupervisor#checkReadyForSleepLocked} again here
        // to ensure any necessary pause logic occurs. In the case where the Activity will be
        // shown regardless of the lock screen, the call to
        // {@link ActivityStackSupervisor#checkReadyForSleepLocked} is skipped.
        final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);
        if (next == null || !next.canTurnScreenOn()) {
            checkReadyForSleep();
        }
    } finally {
        mStackSupervisor.inResumeTopActivity = false;
    }

    return result;
}

该方法中调用了resumeTopActivityInnerLocked方法,resumeTopActivityInnerLocked方法中包含Activity切换调度的核心逻辑。

resumeTopActivityInnerLocked

启动Activity的过程是将Activity置为顶层可见,称为resume top Activity。resumeTopActivityInnerLocked方法中逻辑较多,因此拆解成多步来看。

1.pause当前显示的Activity

[ActivityStack.java]

private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
    if (!mService.mBooting && !mService.mBooted) {
        // ActivityManagerService未启动完成
        // Not ready yet!
        return false;
    }
    
    // Find the next top-most activity to resume in this stack that is not finishing and is
    // focusable. If it is not focusable, we will fall into the case below to resume the
    // top activity in the next focusable task.
    // 将要显示的目标Activity
    final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);
    
    final boolean hasRunningActivity = next != null;

    // TODO: Maybe this entire condition can get removed?
    // 判断是否有ActivityDisplay
    if (hasRunningActivity && !isAttached()) {
        return false;
    }
    
    // 非顶部处于INITIALIZING状态的Activity的AppWindowToken相关的清理动作
    mStackSupervisor.cancelInitializingActivities();
    
    // Remember how we'll process this pause/resume situation, and ensure
    // that the state is reset however we wind up proceeding.
    // 标记是否调用Activity的performUserLeaving回调方法
    boolean userLeaving = mStackSupervisor.mUserLeaving;
    mStackSupervisor.mUserLeaving = false;
    
    if (!hasRunningActivity) {
        // There are no activities left in the stack, let's look somewhere else.
        return resumeTopActivityInNextFocusableStack(prev, options, "noMoreActivities");
    }
    
    // 标记是否延迟显示(AMS在特殊场景中会暂停APP切换)
    next.delayedResume = false;
    
    // 省略比较目标Activity是否已经是当前正在显示的Activity、AMS暂时挂起、UserController判断等部分
    // ···
    
    // The activity may be waiting for stop, but that is no longer
    // appropriate for it.
    // mStoppingActivities保存等待执行stop的Activity
    mStackSupervisor.mStoppingActivities.remove(next);
    mStackSupervisor.mGoingToSleepActivities.remove(next);
    next.sleeping = false;
    mStackSupervisor.mActivitiesWaitingForVisibleActivity.remove(next);
    
    // 判断当前是否存在暂停未完成的Activity
    // If we are currently pausing an activity, then don't do anything until that is done.
    if (!mStackSupervisor.allPausedActivitiesComplete()) {
        if (DEBUG_SWITCH || DEBUG_PAUSE || DEBUG_STATES) Slog.v(TAG_PAUSE,
                "resumeTopActivityLocked: Skip resume: some activity pausing.");
        if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
        return false;
    }
    
    // 设置与wake lock关联的WorkSource,用于应用耗电统计
    mStackSupervisor.setLaunchSource(next.info.applicationInfo.uid);
    
    // 省略画中画判断部分 ···
    
    // pause非当前焦点的ActivityStack中的Activity(若有),将会调用ActivityStack的startPausingLocked方法
    // pausing标记是否有执行pause操作
    boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving, next, false);
    // mResumedActivity表示当前正在显示的Activity。例如Activity A启动Activity B,
    // 则此时mResumedActivity即为Activity A。
    if (mResumedActivity != null) {
        if (DEBUG_STATES) Slog.d(TAG_STATES,
                "resumeTopActivityLocked: Pausing " + mResumedActivity);
        // mResumedActivity不为空,pause这个Activity
        pausing |= startPausingLocked(userLeaving, false, next, false);
    }
    if (pausing && !resumeWhilePausing) {
        // 前面执行了pause activity操作,且未设置FLAG_RESUME_WHILE_PAUSING标识
        // 省略更新mLruProcesses、设置画中画相关部分 ···
        return true;
    } else if (mResumedActivity == next && next.isState(RESUMED)
            && mStackSupervisor.allResumedActivitiesComplete()) {
        // 省略executeAppTransition部分 ···
        return true;
    }
    
    // 省略
    // ···
}

resumeTopActivityInnerLocked方法中第一部分首先会判断当前是否能启动目标Activity,其中比较重要的检查点是判断当前是否需要先执行pause Activity的操作。mResumedActivity记录当前显示的Activity,若它不为空,则执行startPausingLocked方法,然后结束resumeTopActivityInnerLocked方法。

startPausingLocked

此时由Activity A启动Activity B,则需要先pause Activity A,之后才resume Activity B。此处进入startPausingLocked方法,若其中成功执行pause操作,则会返回true,使resumeTopActivityInnerLocked退出执行。

[ActivityStack.java]

final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping,
        ActivityRecord resuming, boolean pauseImmediately) {
    // mPausingActivity表示当前正在pause中的Activity,若存在,则先处理pause善后工作
    if (mPausingActivity != null) {
        Slog.wtf(TAG, "Going to pause when pause is already pending for " + mPausingActivity
                + " state=" + mPausingActivity.getState());
        if (!shouldSleepActivities()) {
            // Avoid recursion among check for sleep and complete pause during sleeping.
            // Because activity will be paused immediately after resume, just let pause
            // be completed by the order of activity paused from clients.
            completePauseLocked(false, resuming);
        }
    }
    // 将当前正在显示的Activity赋值给prev,意味着它将被pause,成为前一个Activity
    ActivityRecord prev = mResumedActivity;
    
    // 省略对prev的检查部分 ···
    
    // prev赋值给mPausingActivity,此时mPausingActivity持有了当前显示的Activity的ActivityRecord引用
    mPausingActivity = prev;
    mLastPausedActivity = prev;
    mLastNoHistoryActivity = (prev.intent.getFlags() & Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
            || (prev.info.flags & ActivityInfo.FLAG_NO_HISTORY) != 0 ? prev : null;
    // 设置prev状态为PAUSING,且会将mResumedActivity置为null
    prev.setState(PAUSING, "startPausingLocked");
    // 更新prev所属Task的最后活动时间
    prev.getTask().touchActiveTime();
    // 超时相关设置
    clearLaunchTime(prev);
    
    // ···
    
    // 判断prev的IApplicationThread是否为空,需要通过它向对应进程通信
    if (prev.app != null && prev.app.thread != null) {
        if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Enqueueing pending pause: " + prev);
        try {
            // ···
            
            // 通知目标应用进程执行对应Activity的生命调度。
            mService.getLifecycleManager().scheduleTransaction(prev.app.thread, prev.appToken,
                    PauseActivityItem.obtain(prev.finishing, userLeaving,
                            prev.configChangeFlags, pauseImmediately));
            // AMS调用Client不阻塞自身,因此发送完binder请求,就继续往下执行。
        } catch (Exception e) {
            // Ignore exception, if process died other code will cleanup.
            Slog.w(TAG, "Exception thrown during pause", e);
            mPausingActivity = null;
            mLastPausedActivity = null;
            mLastNoHistoryActivity = null;
        }
    } else {
        mPausingActivity = null;
        mLastPausedActivity = null;
        mLastNoHistoryActivity = null;
    }
    
    // If we are not going to sleep, we want to ensure the device is
    // awake until the next activity is started.
    if (!uiSleeping && !mService.isSleepingOrShuttingDownLocked()) {
        // 当前未进入休眠状态,则向PowerManagerService申请wakelock使设备一直处于唤醒,并且设置超时消息。
        mStackSupervisor.acquireLaunchWakelock();
    }
    
    // 正常情况此时mPausingActivity仍持有引用
    if (mPausingActivity != null) {
        // Have the window manager pause its key dispatching until the new
        // activity has started.  If we're pausing the activity just because
        // the screen is being turned off and the UI is sleeping, don't interrupt
        // key dispatch; the same activity will pick it up again on wakeup.
        if (!uiSleeping) {
            // 暂停按键事件分发
            prev.pauseKeyDispatchingLocked();
        } else if (DEBUG_PAUSE) {
             Slog.v(TAG_PAUSE, "Key dispatch not paused for screen off");
        }

        // pauseImmediately默认false
        if (pauseImmediately) {
            // If the caller said they don't want to wait for the pause, then complete
            // the pause now.
            completePauseLocked(false, resuming);
            return false;

        } else {
            // 超时设置相关
            schedulePauseTimeout(prev);
            return true;
        }

    } else {
        // This activity failed to schedule the
        // pause, so just treat it as being paused now.
        if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Activity not running, resuming next.");
        // resuming默认持有下一个要显示的ActivityRecord
        if (resuming == null) {
            mStackSupervisor.resumeFocusedStackTopActivityLocked();
        }
        return false;
    }
}

该方法中将mResumedActivity赋值给mPausingActivity,并设置状态为PAUSING,再将mResumedActivity置为null。之后通过IApplicationThread通知对应APP进程执行pause操作。

首先获取PauseActivityItem对象,它继承自ActivityLifecycleItem,表示请求调度Activity的哪个生命阶段。
mService.getLifecycleManager获取ClientLifecycleManager对象,它的作用是辅助分发,进入它的scheduleTransaction方法:

[ClientLifecycleManager.java]

void scheduleTransaction(@NonNull IApplicationThread client, @NonNull IBinder activityToken,
        @NonNull ActivityLifecycleItem stateRequest) throws RemoteException {
    // 创建ClientTransaction,保存client、activityToken、stateRequest参数
    final ClientTransaction clientTransaction = transactionWithState(client, activityToken,
            stateRequest);
    // 该方法中又调用ClientTransaction.schedule()
    scheduleTransaction(clientTransaction);
}

ClientTransaction事务对象,用于封装命令和参数,发送到APP进程处理。ClientTransaction的schedule方法中又调用IApplicationThread的scheduleTransaction方法,并将ClientTransaction实例自身作为入参调用。

scheduleTransaction

AMS通过IApplicationThread调用到APP进程,scheduleTransaction会触发ApplicationThread.scheduleTransaction方法,该方法中又调用ActivityThread的父类ClientTransactionHandler的scheduleTransaction方法:

[ClientTransactionHandler.java]

/** Prepare and schedule transaction for execution. */
void scheduleTransaction(ClientTransaction transaction) {
    transaction.preExecute(this);
    // sendMessage由ActivityThread实现
    sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}

sendMessage是抽象方法由ActivityThread实现,其中又调用另一个sendMessage重载方法:
[ActivityThread.java]

private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
    if (DEBUG_MESSAGES) Slog.v(
        TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
        + ": " + arg1 + " / " + obj);
    Message msg = Message.obtain();
    msg.what = what;
    msg.obj = obj;
    msg.arg1 = arg1;
    msg.arg2 = arg2;
    // async默认为false
    if (async) {
        msg.setAsynchronous(true);
    }
    // 当前处于binder线程,通过mH切换到主线程执行
    mH.sendMessage(msg);
}

该方法中利用mH从binder线程切换到主线程来处理这个事务。在mH的handleMessage方法中的对应case EXECUTE_TRANSACTION中,又通过TransactionExecutor的execute方法来执行ClientTransaction事务消息。

[TransactionExecutor.java]

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

    // 遍历调用ClientTransaction中的mActivityCallbacks成员
    executeCallbacks(transaction);

    // 调用ClientTransaction中的mLifecycleStateRequest成员,即在AMS中设置的PauseActivityItem
    executeLifecycleState(transaction);
    mPendingActions.clear();
    log("End resolving transaction");
}

在executeLifecycleState中,会先后调用PauseActivityItem的executepostExecute方法。其中execute会调用ClientTransactionHandler.handlePauseActivity方法,handlePauseActivity由ActivityThread实现。

handlePauseActivity

[ActivityThread.java]

@Override
public void C(IBinder token, boolean finished, boolean userLeaving,
        int configChanges, PendingTransactionActions pendingActions, String reason) {
    // mActivities保存应用进程的Activity信息,利用token作为key(IBinder除了用于进程间通信,也可用作Key标识)
    // ActivityClientRecord的作用同ActivityRecord,表示APP进程中的Activity信息,
    // 而ActivityRecord表示在AMS中记录的Activity信息。
    ActivityClientRecord r = mActivities.get(token);
    if (r != null) {
        if (userLeaving) {
            // 触发onUserInteraction()和onUserLeaveHint()
            performUserLeavingActivity(r);
        }

        r.activity.mConfigChangeFlags |= configChanges;
        // 执行pause PauseActivity的操作
        performPauseActivity(r, finished, reason, pendingActions);

        // Make sure any pending writes are now committed.
        if (r.isPreHoneycomb()) {
            QueuedWork.waitToFinish();
        }
        mSomeActivitiesChanged = true;
    }
}

performPauseActivity方法中会对ActivityClientRecord中保存的状态进行检查,并视情况调用onSaveInstanceState(),之后又调用performPauseActivityIfNeeded方法:

[ActivityThread.java]

private void performPauseActivityIfNeeded(ActivityClientRecord r, String reason) {
    if (r.paused) {
        // You are already paused silly...
        return;
    }

    try {
        r.activity.mCalled = false;
        // 调用onPause()生命周期回调
        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);
        }
    }
    // 设置ActivityClientRecord的状态为ON_PAUSE
    r.setState(ON_PAUSE);
}

在该方法中通过Instrumentation最终触发了Activity的onPause生命周期回调方法。

当完成了这些操作后,接着将执行PauseActivityItem的postExecute方法:
[PauseActivityItem.java]

@Override
public void postExecute(ClientTransactionHandler client, IBinder token,
        PendingTransactionActions pendingActions) {
    if (mDontReport) {
        return;
    }
    try {
        // TODO(lifecycler): Use interface callback instead of AMS.
        // 通知AMS,pause Activity完成
        ActivityManager.getService().activityPaused(token);
    } catch (RemoteException ex) {
        throw ex.rethrowFromSystemServer();
    }
}

该方法中将调用AMS的activityPaused,再通知回AMS,Activity pause完成。

activityPaused

[ActivityManagerService.java]

@Override
public final void activityPaused(IBinder token) {
    final long origId = Binder.clearCallingIdentity();
    synchronized(this) {
        // 通过token查找ActivityStack
        ActivityStack stack = ActivityRecord.getStackLocked(token);
        if (stack != null) {
            // activityPausedLocked中又会调用completePauseLocked方法
            stack.activityPausedLocked(token, false);
        }
    }
    Binder.restoreCallingIdentity(origId);
}
completePauseLocked

该方法中将调用ActivityStack的completePauseLocked方法,参数传入truenull

[ActivityStack.java]

private void completePauseLocked(boolean resumeNext, ActivityRecord resuming) {
    // 将之前AMS保存的进程pause中的Activity赋值给prev
    ActivityRecord prev = mPausingActivity;
    
    if (prev != null) {
        prev.setWillCloseOrEnterPip(false);
        final boolean wasStopping = prev.isState(STOPPING);
        prev.setState(PAUSED, "completePausedLocked");
        if (prev.finishing) {
            if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Executing finish of activity: " + prev);
            // finish Activity操作
            prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE, false,
                    "completedPausedLocked");
        } else if (prev.app != null) {
            if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Enqueue pending stop if needed: " + prev
                    + " wasStopping=" + wasStopping + " visible=" + prev.visible);
            if (mStackSupervisor.mActivitiesWaitingForVisibleActivity.remove(prev)) {
                if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(TAG_PAUSE,
                        "Complete pause, no longer waiting: " + prev);
            }
            if (prev.deferRelaunchUntilPaused) {
                // Complete the deferred relaunch that was waiting for pause to complete.
                if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Re-launching after pause: " + prev);
                prev.relaunchActivityLocked(false /* andResume */,
                        prev.preserveWindowOnDeferredRelaunch);
            } else if (wasStopping) {
                // We are also stopping, the stop request must have gone soon after the pause.
                // We can't clobber it, because the stop confirmation will not be handled.
                // We don't need to schedule another stop, we only need to let it happen.
                prev.setState(STOPPING, "completePausedLocked");
            } else if (!prev.visible || shouldSleepOrShutDownActivities()) {
                // Clear out any deferred client hide we might currently have.
                prev.setDeferHidingClient(false);
                // If we were visible then resumeTopActivities will release resources before
                // stopping.
                // 添加到ActivityStackSupervisor的mStoppingActivities集合中,
                // 等待后续执行stop Activity操作,并且发送一个IDLE消息。
                addToStopping(prev, true /* scheduleIdle */, false /* idleDelayed */);
            }
        } else {
            if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "App died during pause, not stopping: " + prev);
            prev = null;
        }
        // It is possible the activity was freezing the screen before it was paused.
        // In that case go ahead and remove the freeze this activity has on the screen
        // since it is no longer visible.
        if (prev != null) {
            // 停止屏幕冻结
            prev.stopFreezingScreenLocked(true /*force*/);
        }
        // 取消mPausingActivity引用,表示没有Pausing Activity
        mPausingActivity = null;
    }
    
    // 此时resumeNext值为true,表示要调度resume下一个Activity
    if (resumeNext) {
        final ActivityStack topStack = mStackSupervisor.getFocusedStack();
        // 判断焦点ActivityStack是否不准备休眠、挂起
        if (!topStack.shouldSleepOrShutDownActivities()) {
            mStackSupervisor.resumeFocusedStackTopActivityLocked(topStack, prev, null);
        } else {
            checkReadyForSleep();
            ActivityRecord top = topStack.topRunningActivityLocked();
            if (top == null || (prev != null && top != prev)) {
                // If there are no more activities available to run, do resume anyway to start
                // something. Also if the top activity on the stack is not the just paused
                // activity, we need to go ahead and resume it to ensure we complete an
                // in-flight app switch.
                mStackSupervisor.resumeFocusedStackTopActivityLocked();
            }
        }
    }
    
    // 省略 ···
    
    // 检查更新所有Activity的可见和配置
    mStackSupervisor.ensureActivitiesVisibleLocked(resuming, 0, !PRESERVE_WINDOWS);
}

completePauseLocked方法中会将这次pause的ActivityRecord存入ActivityStackSupervisor的mStoppingActivities成员(ArrayList)中,用于后续再对其执行stop和finish操作。之后将mPausingActivity赋值为null,表示当前没有正在pause的Activity。接着便又调用了resumeFocusedStackTopActivityLocked方法,再次进行resume Activity。

2.判断APP进程是否存在

resumeFocusedStackTopActivityLocked会经过层层调用,回到resumeTopActivityInnerLocked方法中。

回到前面的resumeTopActivityInnerLocked介绍中,此时判断mResumedActivity已经为null(在startPausingLocked中会置为null),因此不进行pause操作,继续往下执行:

[ActivityStack.java]

private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
    // 省略1部分
    // ···
    
    // 省略mLastNoHistoryActivity因休眠而未执行finish的处理部分
    // 省略上一个Activity(即刚刚pause的)的窗口隐藏相关部分
    // ···
    // 省略和WindowManagerService交互、过渡动画相关部分 ···

    // 获取上一个焦点ActivityStack
    ActivityStack lastStack = mStackSupervisor.getLastStack();
    // next表示将要显示的Activity,判断对应APP进程是否存在。
    // 通过缓存的ProcessRecord中的IApplicationThread是否存在来判断,因为需要通过它向APP进程通信。
    if (next.app != null && next.app.thread != null) {
        // If the previous activity is translucent, force a visibility update of
        // the next activity, so that it's added to WM's opening app list, and
        // transition animation can be set up properly.
        // For example, pressing Home button with a translucent activity in focus.
        // Launcher is already visible in this case. If we don't add it to opening
        // apps, maybeUpdateTransitToWallpaper() will fail to identify this as a
        // TRANSIT_WALLPAPER_OPEN animation, and run some funny animation.
        final boolean lastActivityTranslucent = lastStack != null
                && (lastStack.inMultiWindowMode()
                || (lastStack.mLastPausedActivity != null
                && !lastStack.mLastPausedActivity.fullscreen));
        
        // The contained logic must be synchronized, since we are both changing the visibility
        // and updating the {@link Configuration}. {@link ActivityRecord#setVisibility} will
        // ultimately cause the client code to schedule a layout. Since layouts retrieve the
        // current {@link Configuration}, we must ensure that the below code updates it before
        // the layout can occur.
        synchronized(mWindowManager.getWindowManagerLock()) {
            // This activity is now becoming visible.
            if (!next.visible || next.stopped || lastActivityTranslucent) {
                next.setVisibility(true);
            }

            // schedule launch ticks to collect information about slow apps.
            next.startLaunchTickingLocked();

            ActivityRecord lastResumedActivity =
                    lastStack == null ? null :lastStack.mResumedActivity;
            final ActivityState lastState = next.getState();

            mService.updateCpuStats();

            if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to RESUMED: " + next
                    + " (in existing)");

            next.setState(RESUMED, "resumeTopActivityInnerLocked");

            mService.updateLruProcessLocked(next.app, true, null);
            updateLRUListLocked(next);
            mService.updateOomAdjLocked();
            
            // 省略 ···
            
            try {
                // 事务对象,用于封装命令和参数,发送到APP进程处理
                final ClientTransaction transaction = ClientTransaction.obtain(next.app.thread,
                        next.appToken);
                // 省略分发pending results和给ClientTransaction添加Callback部分
                // ···

                next.sleeping = false;
                mService.getAppWarningsLocked().onResumeActivity(next);
                mService.showAskCompatModeDialogLocked(next);
                next.app.pendingUiClean = true;
                next.app.forceProcessStateUpTo(mService.mTopProcessState);
                next.clearOptionsLocked();
                // 设置ResumeActivityItem生命周期执行请求
                transaction.setLifecycleStateRequest(
                        ResumeActivityItem.obtain(next.app.repProcState,
                                mService.isNextTransitionForward()));
               // 调度到APP进程
               mService.getLifecycleManager().scheduleTransaction(transaction);

                if (DEBUG_STATES) Slog.d(TAG_STATES, "resumeTopActivityLocked: Resumed "
                        + next);
            } catch (Exception e) {
                // Whoops, need to restart this activity!
                if (DEBUG_STATES) Slog.v(TAG_STATES, "Resume failed; resetting state to "
                        + lastState + ": " + next);
                next.setState(lastState, "resumeTopActivityInnerLocked");

                // lastResumedActivity being non-null implies there is a lastStack present.
                if (lastResumedActivity != null) {
                    lastResumedActivity.setState(RESUMED, "resumeTopActivityInnerLocked");
                }

                Slog.i(TAG, "Restarting because process died: " + next);
                if (!next.hasBeenLaunched) {
                    next.hasBeenLaunched = true;
                } else  if (SHOW_APP_STARTING_PREVIEW && lastStack != null
                        && lastStack.isTopStackOnDisplay()) {
                    next.showStartingWindow(null /* prev */, false /* newTask */,
                            false /* taskSwitch */);
                }
                // 上面执行发送异常,执行startSpecificActivityLocked方法
                mStackSupervisor.startSpecificActivityLocked(next, true, false);
                if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
                return true;
            }
        }
        
        // 上面resume Activity阶段未发生异常会执行到这里
        // From this point on, if something goes wrong there is no way
        // to recover the activity.
        try {
            // 进行resume操作的善后工作
            next.completeResumeLocked();
        } catch (Exception e) {
            // If any exception gets thrown, toss away this
            // activity and try the next one.
            Slog.w(TAG, "Exception thrown during resume of " + next, e);
            // 发生异常的话就finish该Activity
            requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null,
                    "resume-exception", true);
            if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
            return true;
        }
    } else {
        // Whoops, need to restart this activity!
        if (!next.hasBeenLaunched) {
            next.hasBeenLaunched = true;
        } else {
            if (SHOW_APP_STARTING_PREVIEW) {
                next.showStartingWindow(null /* prev */, false /* newTask */,
                        false /* taskSwich */);
            }
            if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "Restarting: " + next);
        }
        if (DEBUG_STATES) Slog.d(TAG_STATES, "resumeTopActivityLocked: Restarting " + next);
        // APP进程不存在或无效,执行startSpecificActivityLocked
        mStackSupervisor.startSpecificActivityLocked(next, true, true);
    }
    
    if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
    return true;
}

resumeTopActivityInnerLocked方法的下半部分中,判断如果Activity所在进程存在且Activity之前启动过,则直接发送ResumeActivityItem请求通知APP进程进行resume,否则调用ActivityStackSupervisorstartSpecificActivityLocked方法继续执行。

startSpecificActivityLocked

[ActivityStackSupervisor.java]

void startSpecificActivityLocked(ActivityRecord r,
        boolean andResume, boolean checkConfig) {
    // Is this activity's application already running?
    // 查找目标Activity对应的进程信息
    ProcessRecord app = mService.getProcessRecordLocked(r.processName,
            r.info.applicationInfo.uid, true);

    getLaunchTimeTracker().setLaunchTime(r);

    // 判断目标进程是否存在且有效
    if (app != null && app.thread != null) {
        try {
            if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
                    || !"android".equals(r.info.packageName)) {
                // Don't add this if it is a platform component that is marked
                // to run in multiple processes, because this is actually
                // part of the framework so doesn't make sense to track as a
                // separate apk in the process.
                app.addPackage(r.info.packageName, r.info.applicationInfo.longVersionCode,
                        mService.mProcessStats);
            }
            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);
}

该方法中判断目标APP进程若存在,则调用realStartActivityLocked方法继续进行启动流程,否则调用startProcessLocked方法先启动目标进程。

启动目标APP进程

startProcessLocked方法又调用另一个重载方法:

[ActivityManagerService.java]

final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
        boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName,
        boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge,
        String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) {
    long startTime = SystemClock.elapsedRealtime();
    ProcessRecord app;
    
    // 省略bad process相关部分 ···
    // 省略再次判断进程已存在或正在启动相关部分 ···
    
    if (app == null) {
        checkTime(startTime, "startProcess: creating new process record");
        // 创建ProcessRecord实例,并将它添加入AMS.mProcessNames中保存
        app = newProcessRecordLocked(info, processName, isolated, isolatedUid);
        if (app == null) {
            Slog.w(TAG, "Failed making new process record for "
                    + processName + "/" + info.uid + " isolated=" + isolated);
            return null;
        }
        app.crashHandler = crashHandler;
        app.isolatedEntryPoint = entryPoint;
        app.isolatedEntryPointArgs = entryPointArgs;
        checkTime(startTime, "startProcess: done creating new process record");
    } else {
        // If this is a new package in the process, add the package to the list
        app.addPackage(info.packageName, info.versionCode, mProcessStats);
        checkTime(startTime, "startProcess: added package to existing proc");
    }
    
    // 省略系统未就绪情况的部分 ···
    
    checkTime(startTime, "startProcess: stepping in to startProcess");
    // 调用另一个重载方法进一步执行启动进程
    final boolean success = startProcessLocked(app, hostingType, hostingNameStr, abiOverride);
    checkTime(startTime, "startProcess: done starting proc!");
    return success ? app : null;
}

该方法中在进一步调用启动进程前,会先创建ProcessRecord,并保存在AMS的mProcessNames成员中。

startProcessLocked方法中生成startSeqProcessRecord绑定保存,用于检查启动的进程和ProcessRecord是否对应。之后又会经过层层调用,最终通过Process.start请求ZYGOTE创建子APP进程。

APP进程创建和初始化的流程就如《Activity启动流程总结-ActivityThread》,当APP进程创建后会调用AMS的attachApplication方法通知进程启动完成。

APP进程启动完成

[ActivityManagerService.java]

private final boolean attachApplicationLocked(IApplicationThread thread,
        int pid, int callingUid, long startSeq) {
    // ···
    try {
        // 执行ActivityStackSupervisor的attachApplicationLocked方法
        if (mStackSupervisor.attachApplicationLocked(app)) {
            didSomething = true;
        }
    } catch (Exception e) {
        Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
        badApp = true;
    }
    // ···
}

[ActivityStackSupervisor.java]

boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
    final String processName = app.processName;
    // didSomething标记是否有启动组件
    boolean didSomething = false;
    // 遍历ActivityDisplay(一个ActivityDisplay对应一个显示屏幕)
    for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
        final ActivityDisplay display = mActivityDisplays.valueAt(displayNdx);
        for (int stackNdx = display.getChildCount() - 1; stackNdx >= 0; --stackNdx) {
            final ActivityStack stack = display.getChildAt(stackNdx);
            if (!isFocusedStack(stack)) {
                continue;
            }
            stack.getAllRunningVisibleActivitiesLocked(mTmpActivityList);
            final ActivityRecord top = stack.topRunningActivityLocked();
            final int size = mTmpActivityList.size();
            for (int i = 0; i < size; i++) {
                final ActivityRecord activity = mTmpActivityList.get(i);
                if (activity.app == null && app.uid == activity.info.applicationInfo.uid
                        && processName.equals(activity.processName)) {
                    try {
                        // 调用realStartActivityLocked方法启动待resume的Activity
                        if (realStartActivityLocked(activity, app,
                                top == activity /* andResume */, true /* checkConfig */)) {
                            didSomething = true;
                        }
                    } catch (RemoteException e) {
                        Slog.w(TAG, "Exception in new application when starting activity "
                                + top.intent.getComponent().flattenToShortString(), e);
                        throw e;
                    }
                }
            }
        }
    }
    if (!didSomething) {
        ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
    }
    return didSomething;
}

可以看出AMS在收到APP进程启动完成后,会调用realStartActivityLocked启动因为等待目标进程启动而暂缓的Activity。

realStartActivityLocked

[ActivityStackSupervisor.java]

final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
        boolean andResume, boolean checkConfig) throws RemoteException {
    // 检查是否存在pausing中的Activity
    if (!allPausedActivitiesComplete()) {
        // While there are activities pausing we skipping starting any new activities until
        // pauses are complete. NOTE: that we also do this for activities that are starting in
        // the paused state because they will first be resumed then paused on the client side.
        if (DEBUG_SWITCH || DEBUG_PAUSE || DEBUG_STATES) Slog.v(TAG_PAUSE,
                "realStartActivityLocked: Skipping start of r=" + r
                + " some activities pausing...");
        return false;
    }
    
    final TaskRecord task = r.getTask();
    final ActivityStack stack = task.getStack();

    beginDeferResume();
    
    try {
        // ···
        int idx = app.activities.indexOf(r);
        if (idx < 0) {
            app.activities.add(r);
        }
        mService.updateLruProcessLocked(app, true, null);
        mService.updateOomAdjLocked();
        // ···
        try {
            // ···
            
            // Create activity launch transaction.
            final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
                    r.appToken);
            // 创建LaunchActivityItem并添加至mActivityCallbacks成员保存
            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));

            // Set desired final state.
            final ActivityLifecycleItem lifecycleItem;
            // 此时andResume为true,设置ResumeActivityItem为Activity最终期望的状态
            if (andResume) {
                lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
            } else {
                lifecycleItem = PauseActivityItem.obtain();
            }
            // 设置给mLifecycleStateRequest成员
            clientTransaction.setLifecycleStateRequest(lifecycleItem);

            // Schedule transaction.
            // 调用给APP进程
            mService.getLifecycleManager().scheduleTransaction(clientTransaction);
            
            // 省略heavy-weight process相关处理部分 ···
        } catch (RemoteException e) {
            if (r.launchFailed) {
                // This is the second time we failed -- finish activity
                // and give up.
                Slog.e(TAG, "Second failure launching "
                        + r.intent.getComponent().flattenToShortString()
                        + ", giving up", e);
                mService.appDiedLocked(app);
                stack.requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
                        "2nd-crash", false);
                return false;
            }

            // This is the first time we failed -- restart process and
            // retry.
            r.launchFailed = true;
            app.activities.remove(r);
            throw e;
        }
    } finally {
        endDeferResume();
    }
    
    r.launchFailed = false;
    if (stack.updateLRUListLocked(r)) {
        Slog.w(TAG, "Activity " + r + " being launched, but already in LRU list");
    }

    // TODO(lifecycler): Resume or pause requests are done as part of launch transaction,
    // so updating the state should be done accordingly.
    if (andResume && readyToResume()) {
        // As part of the process of launching, ActivityThread also performs
        // a resume.
        // 更新ActivityRecord的状态,以及发送超时消息等操作
        stack.minimalResumeActivityLocked(r);
    } else {
        // This activity is not starting in the resumed state... which should look like we asked
        // it to pause+stop (but remain visible), and it has done so and reported back the
        // current icicle and other state.
        if (DEBUG_STATES) Slog.v(TAG_STATES,
                "Moving to PAUSED: " + r + " (starting in paused state)");
        r.setState(PAUSED, "realStartActivityLocked");
    }

    // Launch the new version setup screen if needed.  We do this -after-
    // launching the initial activity (that is, home), so that it can have
    // a chance to initialize itself while in the background, making the
    // switch back to it faster and look better.
    if (isFocusedStack(stack)) {
        mService.getActivityStartController().startSetupActivity();
    }

    // Update any services we are bound to that might care about whether
    // their client may have activities.
    if (r.app != null) {
        mService.mServices.updateServiceConnectionActivitiesLocked(r.app);
    }

    return true;
}

该方法中创建ClientTransaction对象,先后添加LaunchActivityItemResumeActivityItem两个子项,并发送给APP进程执行相应事务处理。

这个发送接收过程在pause Activity阶段介绍过,最终将在APP进程中调用TransactionExecutor的execute方法,在execute中先遍历处理ClientTransaction的mActivityCallbacks成员,之后处理mLifecycleStateRequest成员。

LaunchActivityItem的处理

这里会先处理LaunchActivityItem,调用它的execute方法,execute中会创建ActivityClientRecord对象,然后调用ActivityThread的handleLaunchActivity方法并传入ActivityClientRecord:

handleLaunchActivity

[ActivityThread.java]

public Activity handleLaunchActivity(ActivityClientRecord r,
        PendingTransactionActions pendingActions, Intent customIntent) {
    // If we are getting ready to gc after going to the background, well
    // we are back active so skip it.
    // 移除GC闲时消息
    unscheduleGcIdler();
    mSomeActivitiesChanged = true;

    // 省略性能监控相关 ···

    // Make sure we are running with the most recent config.
    handleConfigurationChanged(null, null);

    if (localLOGV) Slog.v(
        TAG, "Handling launch of " + r);

    // Initialize before creating the activity
    if (!ThreadedRenderer.sRendererDisabled) {
        GraphicsEnvironment.earlyInitEGL();
    }
    // 初始化WindowManagerGlobal
    WindowManagerGlobal.initialize();

    // 执行启动Activity,并返回Activity实例
    final Activity a = performLaunchActivity(r, customIntent);

    if (a != null) {
        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 {
            // 启动Activity期间发生错误,请求AMS关闭该Activity
            ActivityManager.getService()
                    .finishActivity(r.token, Activity.RESULT_CANCELED, null,
                            Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
    }

    return a;
}

performLaunchActivity

[ActivityThread.java]

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

    // 获取ComponentName
    ComponentName component = r.intent.getComponent();
    if (component == null) {
        // intent中未显式设置,从PackageManagerService中查找匹配的ResolveInfo构建ComponentName
        component = r.intent.resolveActivity(
            mInitialApplication.getPackageManager());
        r.intent.setComponent(component);
    }

    if (r.activityInfo.targetActivity != null) {
        // 若Activity设置了别名(即targetActivity属性),则使用targetActivity构建ComponentName
        component = new ComponentName(r.activityInfo.packageName,
                r.activityInfo.targetActivity);
    }
    
    // 获取ContextImpl实例
    ContextImpl appContext = createBaseContextForActivity(r);
    Activity activity = null;
    try {
        java.lang.ClassLoader cl = appContext.getClassLoader();
        // 获取反射实例化Activity
        activity = mInstrumentation.newActivity(
                cl, component.getClassName(), r.intent);
        StrictMode.incrementExpectedActivityCount(activity.getClass());
        r.intent.setExtrasClassLoader(cl);
        r.intent.prepareToEnterProcess();
        if (r.state != null) {
            r.state.setClassLoader(cl);
        }
    } catch (Exception e) {
        if (!mInstrumentation.onException(activity, e)) {
            throw new RuntimeException(
                "Unable to instantiate activity " + component
                + ": " + e.toString(), e);
        }
    }
    
    try {
        // 获取LoadedApk中缓存的Application对象(在APP进程启动时实例化)
        Application app = r.packageInfo.makeApplication(false, mInstrumentation);

        // ···

        if (activity != null) {
            CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
            Configuration config = new Configuration(mCompatConfiguration);
            if (r.overrideConfig != null) {
                config.updateFrom(r.overrideConfig);
            }
            if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
                    + r.activityInfo.name + " with config " + config);
            Window window = null;
            if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
                window = r.mPendingRemoveWindow;
                r.mPendingRemoveWindow = null;
                r.mPendingRemoveWindowManager = null;
            }
            // 将activity赋值给ContextImpl的mOuterContext成员,使ContextImpl持有activity引用
            appContext.setOuterContext(activity);
            // 进行Activity的成员赋值和初始化等操作
            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);

            if (customIntent != null) {
                activity.mIntent = customIntent;
            }
            r.lastNonConfigurationInstances = null;
            checkAndBlockForNetworkAccess();
            activity.mStartedActivity = false;
            int theme = r.activityInfo.getThemeResource();
            if (theme != 0) {
                // 设置主题
                activity.setTheme(theme);
            }

            activity.mCalled = false;
            if (r.isPersistable()) {
                // 设置了persistable模式,将触发两个参数的onCreate生命周期回调方法
                mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
            } else {
                // 触发带一个入参的onCreate生命周期回调方法
                mInstrumentation.callActivityOnCreate(activity, r.state);
            }
            if (!activity.mCalled) {
                throw new SuperNotCalledException(
                    "Activity " + r.intent.getComponent().toShortString() +
                    " did not call through to super.onCreate()");
            }
            r.activity = activity;
        }
        // 更新ActivityClientRecord中的状态
        r.setState(ON_CREATE);

        // 保存ActivityClientRecord
        mActivities.put(r.token, r);

    } catch (SuperNotCalledException e) {
        throw e;

    } catch (Exception e) {
        if (!mInstrumentation.onException(activity, e)) {
            throw new RuntimeException(
                "Unable to start activity " + component
                + ": " + e.toString(), e);
        }
    }

    return activity;
}

该方法中先后实例化ContextImplActivity,并设置互相间的绑定关系,最后触发onCreate生命周期回调。当执行完这一切后,ActivityClientRecord中mLifecycleState成员(生命周期状态)被设置为ON_CREATE

ContextImpl的创建

这里先看下如何获取和实例化ContextImpl,在createBaseContextForActivity方法中通过ContextImpl.createActivityContext获取ContextImpl实例:
[ContextImpl.java]

static ContextImpl createActivityContext(ActivityThread mainThread,
        LoadedApk packageInfo, ActivityInfo activityInfo, IBinder activityToken, int displayId,
        Configuration overrideConfiguration) {
    if (packageInfo == null) throw new IllegalArgumentException("packageInfo");

    // 省略split apk部分 ···

    // 实例化ContextImpl,并初始化相关成员
    ContextImpl context = new ContextImpl(null, mainThread, packageInfo, activityInfo.splitName,
            activityToken, null, 0, classLoader);

    // Clamp display ID to DEFAULT_DISPLAY if it is INVALID_DISPLAY.
    displayId = (displayId != Display.INVALID_DISPLAY) ? displayId : Display.DEFAULT_DISPLAY;

    final CompatibilityInfo compatInfo = (displayId == Display.DEFAULT_DISPLAY)
            ? packageInfo.getCompatibilityInfo()
            : CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO;

    // 获取ResourcesManager单例对象
    final ResourcesManager resourcesManager = ResourcesManager.getInstance();

    // Create the base resources for which all configuration contexts for this Activity
    // will be rebased upon.
    // 初始化mResources成员
    context.setResources(resourcesManager.createBaseActivityResources(activityToken,
            packageInfo.getResDir(),
            splitDirs,
            packageInfo.getOverlayDirs(),
            packageInfo.getApplicationInfo().sharedLibraryFiles,
            displayId,
            overrideConfiguration,
            compatInfo,
            classLoader));
    context.mDisplay = resourcesManager.getAdjustedDisplay(displayId,
            context.getResources());
    return context;
}
Activity的attach

[Activity.java]

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) {
    attachBaseContext(context);

    // Fragment相关初始化
    mFragments.attachHost(null /*parent*/);
 
    // 初始化PhoneWindow
    mWindow = new PhoneWindow(this, window, activityConfigCallback);
    mWindow.setWindowControllerCallback(this);
    mWindow.setCallback(this);
    mWindow.setOnWindowDismissedCallback(this);
    mWindow.getLayoutInflater().setPrivateFactory(this);
    if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
        mWindow.setSoftInputMode(info.softInputMode);
    }
    if (info.uiOptions != 0) {
        mWindow.setUiOptions(info.uiOptions);
    }
    // 指定当前运行线程为UiThread
    mUiThread = Thread.currentThread();

    mMainThread = aThread;
    mInstrumentation = instr;
    mToken = token;
    mIdent = ident;
    mApplication = application;
    mIntent = intent;
    mReferrer = referrer;
    mComponent = intent.getComponent();
    mActivityInfo = info;
    mTitle = title;
    mParent = parent;
    mEmbeddedID = id;
    mLastNonConfigurationInstances = lastNonConfigurationInstances;
    // 语音交互相关
    if (voiceInteractor != null) {
        if (lastNonConfigurationInstances != null) {
            mVoiceInteractor = lastNonConfigurationInstances.voiceInteractor;
        } else {
            mVoiceInteractor = new VoiceInteractor(voiceInteractor, this, this,
                    Looper.myLooper());
        }
    }

    // 获取WindowManagerService
    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);

    setAutofillCompatibilityEnabled(application.isAutofillCompatibilityEnabled());
    enableAutofillCompatibilityIfNeeded();
}

ResumeActivityItem的处理

在LaunchActivityItem处理完后,便轮到了ResumeActivityItem。

进入TransactionExecutor的executeLifecycleState方法:
[TransactionExecutor.java]

private void executeLifecycleState(ClientTransaction transaction) {
    // 此时的lifecycleItem为ResumeActivityItem
    final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
    if (lifecycleItem == null) {
        // No lifecycle request, return early.
        return;
    }
    log("Resolving lifecycle state: " + lifecycleItem);

    final IBinder token = transaction.getActivityToken();
    // 根据token取出缓存的ActivityClientRecord
    final ActivityClientRecord r = mTransactionHandler.getActivityClient(token);

    if (r == null) {
        // Ignore requests for non-existent client records for now.
        return;
    }

    // Cycle to the state right before the final requested state.
    // 该方法中会按生命周期顺序补充执行对应生命周期阶段的方法
    cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */);

    // Execute the final transition with proper parameters.
    lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
    lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
}

经过上面performLaunchActivity方法的处理,此时Activity的状态为ON_CREATE,但是ResumeActivityItem中保存的期望状态是ON_RESUME,在cycleToPath方法中会先调用handleStartActivity方法,进行Activity start阶段的处理。

handleStartActivity

[ActivityThread.java]

public void handleStartActivity(ActivityClientRecord r,
        PendingTransactionActions pendingActions) {
    final Activity activity = r.activity;
    // 状态检查
    if (r.activity == null) {
        // TODO(lifecycler): What do we do in this case?
        return;
    }
    if (!r.stopped) {
        throw new IllegalStateException("Can't start activity that is not stopped.");
    }
    if (r.activity.mFinished) {
        // TODO(lifecycler): How can this happen?
        return;
    }

    // Start
    // performStart方法中会通过Instrumentation调用Activity的onStart生命周期回调方法
    activity.performStart("handleStartActivity");
    // 设置生命周期状态为ON_START
    r.setState(ON_START);

    if (pendingActions == null) {
        // No more work to do.
        return;
    }

    // Restore instance state
    if (pendingActions.shouldRestoreInstanceState()) {
        // 将回调onRestoreInstanceState生命周期方法
        if (r.isPersistable()) {
            if (r.state != null || r.persistentState != null) {
                mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
                        r.persistentState);
            }
        } else if (r.state != null) {
            mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
        }
    }

    // Call postOnCreate()
    if (pendingActions.shouldCallOnPostCreate()) {
        activity.mCalled = false;
        if (r.isPersistable()) {
            mInstrumentation.callActivityOnPostCreate(activity, r.state,
                    r.persistentState);
        } else {
            mInstrumentation.callActivityOnPostCreate(activity, r.state);
        }
        if (!activity.mCalled) {
            throw new SuperNotCalledException(
                    "Activity " + r.intent.getComponent().toShortString()
                            + " did not call through to super.onPostCreate()");
        }
    }
}

该方法中调用了onStart生命周期方法,并将Activity生命周期状态设置为ON_START。

handleResumeActivity

接下来执行ResumeActivityItem的execute方法,其中又调用handleResumeActivity方法:

[ActivityThread.java]

public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
        String reason) {
    // If we are getting ready to gc after going to the background, well
    // we are back active so skip it.
    unscheduleGcIdler();
    mSomeActivitiesChanged = true;
    
    // TODO Push resumeArgs into the activity for consideration
    // 该方法中首先视情况调用onRestart生命周期回调方法,接着调用onResume生命周期方法,
    // 设置状态为ON_RESUME,最后返回缓存的ActivityClientRecord。
    final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
    if (r == null) {
        // We didn't actually resume the activity, so skipping any follow-up actions.
        return;
    }
    
    // 省略初始化DecorView、ViewRootImpl、向WindowManagerService注册窗口等操作部分
    // ···
    
    r.nextIdle = mNewActivities;
    mNewActivities = r;
    // 往当前线程添加一个闲时消息
    Looper.myQueue().addIdleHandler(new Idler());
}

该方法中将回调onResume生命周期方法,并设置生命周期状态为ON_RESUME。如果当前Activity是首次启动,则还需要进行DecorView、ViewRootImpl、WindowManager相关初始化操作,向WindowManagerService注册窗口,设置视图树可见。
在该方法下半部分的源码中(此处省略)可以得知,Activity首次启动的时候是在onResume后才真正可见,并不是onStart时就部分可见。

该方法最后,往当前线程Looper中的消息队列中添加一个闲时消息Idler,当消息队列中无消息处理时将回调它的queueIdle方法,在queueIdle中又会通过IActivityManager调用AMS的activityIdle方法

activityIdle

APP进程通过activityIdle方法通知AMS目标Activity的resume操作完成,其中会根据token取得对应的ActivityStack,调用它的activityIdleInternalLocked方法:
[ActivityStackSupervisor.java]

final ActivityRecord activityIdleInternalLocked(final IBinder token, boolean fromTimeout,
        boolean processPausingActivities, Configuration config) {
    if (DEBUG_ALL) Slog.v(TAG, "Activity idle: " + token);

    ArrayList<ActivityRecord> finishes = null;
    ArrayList<UserState> startingUsers = null;
    int NS = 0;
    int NF = 0;
    boolean booting = false;
    boolean activityRemoved = false;
    
    ActivityRecord r = ActivityRecord.forTokenLocked(token);
    if (r != null) {
        // 移除超时消息
        mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
        // 省略
        // ···
        r.idle = true;
    }
    
    // 省略检查resumedActivity的idle相关部分 ···
    
    // Atomically retrieve all of the other things to do.
    // 获取paused的ActivityRecord集合(Activity pause后会加入mStoppingActivities保存)
    final ArrayList<ActivityRecord> stops = processStoppingActivitiesLocked(r,
            true /* remove */, processPausingActivities);
    NS = stops != null ? stops.size() : 0;
    if ((NF = mFinishingActivities.size()) > 0) {
        // mFinishingActivities保存已经stop,等待finish的ActivityRecord
        finishes = new ArrayList<>(mFinishingActivities);
        mFinishingActivities.clear();
    }
    // 省略 ···
    
    // Stop any activities that are scheduled to do so but have been
    // waiting for the next one to start.
    for (int i = 0; i < NS; i++) {
        // 依次取出ActivityRecord,对其执行stop或finish操作
        r = stops.get(i);
        final ActivityStack stack = r.getStack();
        if (stack != null) {
            // 
            if (r.finishing) {
                stack.finishCurrentActivityLocked(r, ActivityStack.FINISH_IMMEDIATELY, false,
                        "activityIdleInternalLocked");
            } else {
                stack.stopActivityLocked(r);
            }
        }
    }
    
    // Finish any activities that are scheduled to do so but have been
    // waiting for the next one to start.
    for (int i = 0; i < NF; i++) {
        r = finishes.get(i);
        final ActivityStack stack = r.getStack();
        if (stack != null) {
            // 销毁APP进程中的Activity实例
            activityRemoved |= stack.destroyActivityLocked(r, true, "finish-idle");
        }
    }
    
    // 省略 ···
    
    mService.trimApplications();
    //dump();
    //mWindowManager.dump();

    if (activityRemoved) {
        resumeFocusedStackTopActivityLocked();
    }

    return r;
}

该方法中获取之前保存的等待stop或finish的ActivityRecord,执行相应的操作。

stopActivityLocked

[ActivityStack.java]

final void stopActivityLocked(ActivityRecord r) {
    // 省略FLAG_ACTIVITY_NO_HISTORY、FLAG_NO_HISTORY相关部分 ···
    if (r.app != null && r.app.thread != null) {
        adjustFocusedActivityStack(r, "stopActivity");
        r.resumeKeyDispatchingLocked();
        try {
            r.stopped = false;
            if (DEBUG_STATES) Slog.v(TAG_STATES,
                    "Moving to STOPPING: " + r + " (stop requested)");
            r.setState(STOPPING, "stopActivityLocked");
            if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY,
                    "Stopping visible=" + r.visible + " for " + r);
            if (!r.visible) {
                r.setVisible(false);
            }
            EventLogTags.writeAmStopActivity(
                    r.userId, System.identityHashCode(r), r.shortComponentName);
            // 使用StopActivityItem封装事务,调度到APP进程
            mService.getLifecycleManager().scheduleTransaction(r.app.thread, r.appToken,
                    StopActivityItem.obtain(r.visible, r.configChangeFlags));
            if (shouldSleepOrShutDownActivities()) {
                r.setSleeping(true);
            }
            // 发送超时消息
            Message msg = mHandler.obtainMessage(STOP_TIMEOUT_MSG, r);
            mHandler.sendMessageDelayed(msg, STOP_TIMEOUT);
        } catch (Exception e) {
            // Maybe just ignore exceptions here...  if the process
            // has crashed, our death notification will clean things
            // up.
            Slog.w(TAG, "Exception thrown during pause", e);
            // Just in case, assume it to be stopped.
            r.stopped = true;
            if (DEBUG_STATES) Slog.v(TAG_STATES, "Stop failed; moving to STOPPED: " + r);
            r.setState(STOPPED, "stopActivityLocked");
            if (r.deferRelaunchUntilPaused) {
                destroyActivityLocked(r, true, "stop-except");
            }
        }
    }
}

handleStopActivity

stopActivityLocked方法中发送ClientTransaction到对应APP进程(之前pause的Activity所在进程),然后调用StopActivityItem的execute方法,其中将调用ActivityThread的handleStopActivity方法:

[ActivityThread.java]

public void handleStopActivity(IBinder token, boolean show, int configChanges,
        PendingTransactionActions pendingActions, boolean finalStateRequest, String reason) {
    // 通过token查找ActivityClientRecord(之前pause的Activity)
    final ActivityClientRecord r = mActivities.get(token);
    r.activity.mConfigChangeFlags |= configChanges;

    // 继承自Runnable,用于保存stop相关参数和通知AMS结果
    final StopInfo stopInfo = new StopInfo();
    // 将调用onStop生命周期回调方法,设置状态为ON_STOP,视情况调用onSaveInstanceState回调方法
    performStopActivityInner(r, stopInfo, show, true /* saveState */, finalStateRequest,
            reason);

    if (localLOGV) Slog.v(
        TAG, "Finishing stop of " + r + ": show=" + show
        + " win=" + r.window);

    updateVisibility(r, show);

    // Make sure any pending writes are now committed.
    if (!r.isPreHoneycomb()) {
        QueuedWork.waitToFinish();
    }

    stopInfo.setActivity(r);
    stopInfo.setState(r.state);
    stopInfo.setPersistentState(r.persistentState);
    // 将stopInfo添加至pendingActions保存
    pendingActions.setStopInfo(stopInfo);
    mSomeActivitiesChanged = true;
}

该方法中创建StopInfo保存stop过程相关参数,接着调用performStopActivityInner方法,在其中会调用onStop生命周期回调方法,设置状态为ON_STOP,视情况调用onSaveInstanceState回调方法。方法最后将stopInfo添加进pendingActions保存。

reportStop

StopActivityItem在执行完execute方法后,会执行postExecute方法,而在这个方法中会调用ActivityThread的reportStop方法:
[ActivityThread.java]

public void reportStop(PendingTransactionActions pendingActions) {
    mH.post(pendingActions.getStopInfo());
}

可以看到,这里从pendingActions中取出先前保存的StopInfo,切换到主线程执行。StopInfo继承自Runnable,将触发它的run方法:
[PendingTransactionActions.java]

public void run() {
    // Tell activity manager we have been stopped.
    try {
        if (DEBUG_MEMORY_TRIM) Slog.v(TAG, "Reporting activity stopped: " + mActivity);
        // TODO(lifecycler): Use interface callback instead of AMS.
        // 调用AMS的activityStopped方法以通知AMS
        ActivityManager.getService().activityStopped(
                mActivity.token, mState, mPersistentState, mDescription);
    } catch (RemoteException ex) {
        // 省略异常处理部分 ···
    }

activityStoppedLocked

AMS的activityStopped方法中会根据token查找对应的ActivityRecord,再调用其activityStoppedLocked方法:
[ActivityRecord.java]

final void activityStoppedLocked(Bundle newIcicle, PersistableBundle newPersistentState,
        CharSequence description) {
    final ActivityStack stack = getStack();
    if (mState != STOPPING) {
        Slog.i(TAG, "Activity reported stop, but no longer stopping: " + this);
        // 移除超时消息
        stack.mHandler.removeMessages(STOP_TIMEOUT_MSG, this);
        return;
    }
    
    // 省略
    // ···
    
    if (!stopped) {
        if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to STOPPED: " + this + " (stop complete)");
        stack.mHandler.removeMessages(STOP_TIMEOUT_MSG, this);
        stopped = true;
        setState(STOPPED, "activityStoppedLocked");

        mWindowContainerController.notifyAppStopped();

        if (finishing) {
            clearOptionsLocked();
        } else {
            if (deferRelaunchUntilPaused) {
                stack.destroyActivityLocked(this, true /* removeFromApp */, "stop-config");
                mStackSupervisor.resumeFocusedStackTopActivityLocked();
            } else {
                mStackSupervisor.updatePreviousProcessLocked(this);
            }
        }
    }
}

到这里完成了Activity的stop操作和通知AMS。

总结

时序图

启动Activity的大致的流程如图所示,AMS负责调度各Activity的生命周期,Activity执行完某一阶段后,也需要通知到AMS,以便AMS进行下一步调度。
这个时序图也印证了开头前言中 Activity A 启动 Activity B 的生命周期顺序的结论确实是这样的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章