AMS-stack(二) ActivityStack

由于篇幅问题第一篇介绍了栈的大管家,这篇介绍stack,ActivityStack类也比较恐怖有五千行代码,不过ActivityStack主要负对task的管理,对activity的管理,为ActivityStackSupervisor做了很多更底层的事情,对整个activity的管理最重要和繁多的一个环节,我们要想学习wms必须先搞清楚stack的逻辑,再搞清楚task的逻辑,最后将ams的情景进行总结,根据不同的情景再次走一次,加深印象。

首先还是先看stack维护的数据结构

 enum ActivityState {
        INITIALIZING,
        RESUMED,
        PAUSING,
        PAUSED,
        STOPPING,
        STOPPED,
        FINISHING,
        DESTROYING,
        DESTROYED
    }
  • 从ActivityState这个枚举值可以看到,一个actviity的生命周期包括上面的9个状态,stack正式负责这九个状态的切换。
  • stack的可见状态如下
    //不可见
    static final int STACK_INVISIBLE = 0;
    // 可见
    static final int STACK_VISIBLE = 1;
    //可见但是被其他stack遮挡,如透明的activity
    static final int STACK_VISIBLE_ACTIVITY_BEHIND = 2;
  • 移除task的模式也有三种
  // 销毁
  static final int REMOVE_TASK_MODE_DESTROYING = 0;
    //移动,不执行一些操作,例如不从wms中移除或者最近任务移除
    static final int REMOVE_TASK_MODE_MOVING = 1;
  // 把task移动到stack顶部,把stack启动到前台
    static final int REMOVE_TASK_MODE_MOVING_TO_TOP = 2;
  • private final ArrayList mTaskHistory = new ArrayList<>(); task的记录
  • final ArrayList mValidateAppTokens = new ArrayList<>(); 
  • final ArrayList mLRUActivities = new ArrayList<>(); 最近最少使用的activity
  • final ArrayList mNoAnimActivities = new ArrayList<>(); 不执行activity切换动画的activity
  • ActivityRecord mPausingActivity = null; 正在执行pause的activity
  • ActivityRecord mLastPausedActivity = null; 最后一个执行pause的activity
  • ActivityRecord mLastNoHistoryActivity = null; 用户指定不显示在历史记录的activity
  • ActivityRecord mResumedActivity = null; 当先正在显示的activity
  • boolean mFullscreen = true; 堆栈是否覆盖整个屏幕
  • Rect mBounds = null; stack的大小,全屏时候为空
  • boolean mUpdateBoundsDeferred; 延迟更新边界
  • boolean mUpdateBoundsDeferredCalled; 延迟更新被调用
 final Rect mDeferredBounds = new Rect();
    final Rect mDeferredTaskBounds = new Rect();
    final Rect mDeferredTaskInsetBounds = new Rect();

同样Stack中也存在一个Handler,运行在AMS的mainHandler所在的线程中,主要的工作还是对超时的处理

  final class ActivityStackHandler extends Handler {

        ActivityStackHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case PAUSE_TIMEOUT_MSG: { //pause activity超时
                    ActivityRecord r = (ActivityRecord)msg.obj;
                    // We don't at this point know if the activity is fullscreen,
                    // so we need to be conservative and assume it isn't.
                    Slog.w(TAG, "Activity pause timeout for " + r);
                    synchronized (mService) { 
                        if (r.app != null) {
                            mService.logAppTooSlow(r.app, r.pauseTime, "pausing " + r);
                        }
                        activityPausedLocked(r.appToken, true);
                    }
                } break;
                case LAUNCH_TICK_MSG: { // 启动时间太长 记录log,user版本不会打印
                    ActivityRecord r = (ActivityRecord)msg.obj;
                    synchronized (mService) {
                        if (r.continueLaunchTickingLocked()) {
                            mService.logAppTooSlow(r.app, r.launchTickTime, "launching " + r);
                        }
                    }
                } break;
                case DESTROY_TIMEOUT_MSG: {//销毁超时
                    ActivityRecord r = (ActivityRecord)msg.obj;
                    // We don't at this point know if the activity is fullscreen,
                    // so we need to be conservative and assume it isn't.
                    Slog.w(TAG, "Activity destroy timeout for " + r);
                    synchronized (mService) {
                        activityDestroyedLocked(r != null ? r.appToken : null, "destroyTimeout");
                    }
                } break;
                case STOP_TIMEOUT_MSG: { // 停止超时
                    ActivityRecord r = (ActivityRecord)msg.obj;
                    // We don't at this point know if the activity is fullscreen,
                    // so we need to be conservative and assume it isn't.
                    Slog.w(TAG, "Activity stop timeout for " + r);
                    synchronized (mService) {
                        if (r.isInHistory()) {
                            activityStoppedLocked(r, null, null, null);
                        }
                    }
                } break;
                case DESTROY_ACTIVITIES_MSG: { //执行销毁activity
                    ScheduleDestroyArgs args = (ScheduleDestroyArgs)msg.obj;
                    synchronized (mService) {
                        destroyActivitiesLocked(args.mOwner, args.mReason);
                    }
                } break;
                case TRANSLUCENT_TIMEOUT_MSG: {//设置半透明超时
                    synchronized (mService) {
                        notifyActivityDrawnLocked(null);
                    }
                } break;
                case RELEASE_BACKGROUND_RESOURCES_TIMEOUT_MSG: { //取消后台显示超时
                    synchronized (mService) {
                        final ActivityRecord r = getVisibleBehindActivity();
                        Slog.e(TAG, "Timeout waiting for cancelVisibleBehind player=" + r);
                        if (r != null) {
                            mService.killAppAtUsersRequest(r.app, null);
                        }
                    }
                } break;
            }
        }
    }

这一又一次验证了系统服务不能保证客户端高效可靠的执行,全部用超时处理

  • int numActivities() 函数返回stack中有多少个activity
  • 下面来看一下构造函数
 ActivityStack(ActivityStackSupervisor.ActivityContainer activityContainer,
            RecentTasks recentTasks) {
        mActivityContainer = activityContainer; //所在的activity container
        mStackSupervisor = activityContainer.getOuter(); // 栈大管家赋值
        mService = mStackSupervisor.mService; //AMS
        mHandler = new ActivityStackHandler(mService.mHandler.getLooper()); //Handler创建
        mWindowManager = mService.mWindowManager; //WMS赋值
        mStackId = activityContainer.mStackId; // stackid
        mCurrentUser = mService.mUserController.getCurrentUserIdLocked(); //当前user
        mRecentTasks = recentTasks; //recent task
        mTaskPositioner = mStackId == FREEFORM_WORKSPACE_STACK_ID
                ? new LaunchingTaskPositioner() : null; //freeform stack需要使用LaunchingTaskPositioner计算位置
    }

在看看stack创建和销毁的操作
stack创建后会马上attach display上面

void attachDisplay(ActivityStackSupervisor.ActivityDisplay activityDisplay, boolean onTop) {
        mDisplayId = activityDisplay.mDisplayId;
        mStacks = activityDisplay.mStacks;
        //mBounds会通过WMS返回,wms会根据docker stack情况计算出新的stack大小
        mBounds = mWindowManager.attachStack(mStackId, activityDisplay.mDisplayId, onTop);
        mFullscreen = mBounds == null;
        if (mTaskPositioner != null) {// freedom stack的一些处理
            mTaskPositioner.setDisplay(activityDisplay.mDisplay);
            mTaskPositioner.configure(mBounds);
        }

        if (mStackId == DOCKED_STACK_ID) {//更新docker stack大小
            // If we created a docked stack we want to resize it so it resizes all other stacks
            // in the system.
            mStackSupervisor.resizeDockedStackLocked(
                    mBounds, null, null, null, null, PRESERVE_WINDOWS);
        }
    }
  //从display上移除stack
    void detachDisplay() {
        mDisplayId = Display.INVALID_DISPLAY;
        mStacks = null;
        if (mTaskPositioner != null) {
            mTaskPositioner.reset();
        }
        //WMS先移除
        mWindowManager.detachStack(mStackId);
        if (mStackId == DOCKED_STACK_ID) { //更新其他 stack大小
            // If we removed a docked stack we want to resize it so it resizes all other stacks
            // in the system to fullscreen.
            mStackSupervisor.resizeDockedStackLocked(
                    null, null, null, null, null, PRESERVE_WINDOWS);
        }
    }
  • 后面一些列deferUpdateBounds的操作的作用是在activity启动的时候不去更新HOME STACK的大小,直到app动画执行完成的时候再去更新,其中有三个函数,void deferUpdateBounds()表示开始执行延迟更新,而在resize的过程中,先不更新stack的边界,使用boolean updateBoundsAllowed(Rect bounds, Rect tempTaskBounds,
    Rect tempTaskInsetBounds)函数记录边界,并且设置mUpdateBoundsDeferredCalled = true;表示边界有更新,最后在activity切换动画执行完成后,使用void continueUpdateBounds()更新stack边界。

  • setBounds函数设置stack的大小

 void setBounds(Rect bounds) {
        mBounds = mFullscreen ? null : new Rect(bounds);
        if (mTaskPositioner != null) {
            mTaskPositioner.configure(bounds);
        }
    }
  • final ActivityRecord topRunningActivityLocked()  返回最stack最上面没有finish并且user可以显示的activity
  • final ActivityRecord topRunningNonDelayedActivityLocked(ActivityRecord notTop) 返回不延迟显示的activity
  • final ActivityRecord topActivity() 返回没有finish的activity,不管user是不是可以显示
  • final TaskRecord topTask()
  • TaskRecord taskForIdLocked(int id)  根据id找task
  • ActivityRecord isInStackLocked(ActivityRecord r) 返回activity是否在stack中
  • moveToFront函数把stack移动到前台,并且如果指定了tsak参数,把task移动到前台
  /**
     * @param reason The reason for moving the stack to the front.
     * @param task If non-null, the task will be moved to the top of the stack.
     * */
    void moveToFront(String reason, TaskRecord task) {
        if (!isAttached()) {//1 没有attach不操作
            return;
        }

        mStacks.remove(this);
        int addIndex = mStacks.size();

        if (addIndex > 0) {
            final ActivityStack topStack = mStacks.get(addIndex - 1);
            if (StackId.isAlwaysOnTop(topStack.mStackId) && topStack != this) {
            //2 画中画的stack永远在最上面,添加到倒数第二个的位置
                // If the top stack is always on top, we move this stack just below it.
                addIndex--;
            }
        }
        //3 添加到计算出的位置
        mStacks.add(addIndex, this);

        // TODO(multi-display): Needs to also work if focus is moving to the non-home display.
        if (isOnHomeDisplay()) { //4 设置为焦点stack
            mStackSupervisor.setFocusStackUnchecked(reason, this);
        }
        if (task != null) { 
            insertTaskAtTop(task, null);
        } else {
            task = topTask();
        }
        //4移动task到顶部,通过WMS移动window
        if (task != null) {
            mWindowManager.moveTaskToTop(task.taskId);
        }
    }
  • isFocusable 返回stack是否能够获取焦点,除了画中画所在的stack,其他都默认可以接收事件,获取焦点。 对于画中画所在的stack要看它的top activity能否获取焦点
  • findTaskLocked函数比较重要,是在startActivity过程中寻找复用的task过程中使用的函数
void findTaskLocked(ActivityRecord target, FindTaskResult result) {
        Intent intent = target.intent;
        ActivityInfo info = target.info;
        ComponentName cls = intent.getComponent();
        if (info.targetActivity != null) {
        //1 指定了targetActivity的情况以target为准,
        //AndroidManifest中可以配置,一种解耦的手段
            cls = new ComponentName(info.packageName, info.targetActivity);
        }
        //2 document task的话要匹配指定的data,所以这里获取documentData
        final int userId = UserHandle.getUserId(info.applicationInfo.uid);
        boolean isDocument = intent != null & intent.isDocument();
        // If documentData is non-null then it must match the existing task data.
        Uri documentData = isDocument ? intent.getData() : null;

        if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Looking for task of " + target + " in " + this);
        //3 遍历task,只是匹配task的top activity
        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
            final TaskRecord task = mTaskHistory.get(taskNdx);
            //4 voiceSession不做考虑
            if (task.voiceSession != null) {
                // We never match voice sessions; those always run independently.
                if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Skipping " + task + ": voice session");
                continue;
            }
            //5 user不匹配不做考虑
            if (task.userId != userId) {
                // Looking for a different task.
                if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Skipping " + task + ": different user");
                continue;
            }
            //6 空task,finish的activity和user不匹配,LAUNCH_SINGLE_INSTANCE的activity不匹配。LAUNCH_SINGLE_INSTANCE的情况使用另外一个函数寻找
            final ActivityRecord r = task.getTopActivity();
            if (r == null || r.finishing || r.userId != userId ||
                    r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
                if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Skipping " + task + ": mismatch root " + r);
                continue;
            }
            //7 类型不匹配的跳过
            if (r.mActivityType != target.mActivityType) {
                if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Skipping " + task + ": mismatch activity type");
                continue;
            }

            final Intent taskIntent = task.intent;
            final Intent affinityIntent = task.affinityIntent;
            final boolean taskIsDocument;
            final Uri taskDocumentData;
            //8 计算task的document模式和data
            if (taskIntent != null && taskIntent.isDocument()) {
                taskIsDocument = true;
                taskDocumentData = taskIntent.getData();
            } else if (affinityIntent != null && affinityIntent.isDocument()) {
                taskIsDocument = true;
                taskDocumentData = affinityIntent.getData();
            } else {
                taskIsDocument = false;
                taskDocumentData = null;
            }

            if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Comparing existing cls="
                    + taskIntent.getComponent().flattenToShortString()
                    + "/aff=" + r.task.rootAffinity + " to new cls="
                    + intent.getComponent().flattenToShortString() + "/aff=" + info.taskAffinity);
            // TODO Refactor to remove duplications. Check if logic can be simplified.
            //9 先根据Component查找,优先级最高
            if (taskIntent != null && taskIntent.getComponent() != null &&
                    taskIntent.getComponent().compareTo(cls) == 0 &&
                    Objects.equals(documentData, taskDocumentData)) {
                if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Found matching class!");
                //dump();
                if (DEBUG_TASKS) Slog.d(TAG_TASKS,
                        "For Intent " + intent + " bringing to top: " + r.intent);
                result.r = r;
                result.matchedByRootAffinity = false;
                break;
             //10 按照粘性复用,必须要匹配document data
            } else if (affinityIntent != null && affinityIntent.getComponent() != null &&
                    affinityIntent.getComponent().compareTo(cls) == 0 &&
                    Objects.equals(documentData, taskDocumentData)) {
                if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Found matching class!");
                //dump();
                if (DEBUG_TASKS) Slog.d(TAG_TASKS,
                        "For Intent " + intent + " bringing to top: " + r.intent);
                result.r = r;
                result.matchedByRootAffinity = false;
                break;
            //11 根据rootAffinity匹配,也就是根节点的资源粘性,这种情况不跳出循环,默认的taskAffinity就是包名
            } else if (!isDocument && !taskIsDocument
                    && result.r == null && task.canMatchRootAffinity()) {
                if (task.rootAffinity.equals(target.taskAffinity)) {
                    if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Found matching affinity candidate!");
                    // It is possible for multiple tasks to have the same root affinity especially
                    // if they are in separate stacks. We save off this candidate, but keep looking
                    // to see if there is a better candidate.
                    result.r = r;
                    result.matchedByRootAffinity = true;
                }
            } else if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Not a match: " + task);
        }
    }
  • 这个就是findActivityLocked用于寻找可以复用的activity
ActivityRecord findActivityLocked(Intent intent, ActivityInfo info,
                                      boolean compareIntentFilters) {
        //1 计算目标   ComponentName                          
        ComponentName cls = intent.getComponent();
        if (info.targetActivity != null) {
            cls = new ComponentName(info.packageName, info.targetActivity);
        }
        final int userId = UserHandle.getUserId(info.applicationInfo.uid);
        //2 遍历task
        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
            final TaskRecord task = mTaskHistory.get(taskNdx);
            final boolean notCurrentUserTask =
                    !mStackSupervisor.isCurrentProfileLocked(task.userId);
            final ArrayList<ActivityRecord> activities = task.mActivities;
            //3 遍历activity
            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
                ActivityRecord r = activities.get(activityNdx);
                //4 忽略不匹配的user的tasl
                if (notCurrentUserTask && (r.info.flags & FLAG_SHOW_FOR_ALL_USERS) == 0) {
                    continue;
                }
                //5忽略user不匹配的activity
                if (!r.finishing && r.userId == userId) {
                    if (compareIntentFilters) { //6 匹配intent
                        if (r.intent.filterEquals(intent)) {
                            return r;
                        }
                    } else {
                        //6 不需要匹配intent直接匹配Component, compareIntentFilters中也会匹配component
                        if (r.intent.getComponent().equals(cls)) {
                            return r;
                        }
                    }
                }
            }
        }

        return null;
    }
  • switchUserLocked切换用户所用的的函数,将user对应的activity放在前台
/*
     * Move the activities around in the stack to bring a user to the foreground.
     */
    final void switchUserLocked(int userId) {
        if (mCurrentUser == userId) {
            return;
        }
        mCurrentUser = userId;

        // Move userId's tasks to the top.
        int index = mTaskHistory.size();
        for (int i = 0; i < index; ) {
            final TaskRecord task = mTaskHistory.get(i);

            // NOTE: If {@link TaskRecord#topRunningActivityLocked} return is not null then it is
            // okay to show the activity when locked.
            //1 如果是user profile则允许显示ui,topRunningActivityLocked不为空说明有能运行在该user下的界面
            //这两种情况都允许task运行在前台
            if (mStackSupervisor.isCurrentProfileLocked(task.userId)
                    || task.topRunningActivityLocked() != null) {
                if (DEBUG_TASKS) Slog.d(TAG_TASKS, "switchUserLocked: stack=" + getStackId() +
                        " moving " + task + " to top");
                mTaskHistory.remove(i);
                mTaskHistory.add(task);
                --index;
                // Use same value for i.
            } else {
                ++i;
            }
        }
        //2 经过该循环后user对应的task都在上面了
        if (VALIDATE_TOKENS) {
            validateAppTokensLocked();
        }
    }
  • 最小化启动操作,该函数在直接调用客户端的lunchActivity的过程中调用resume后设置resume完成
void minimalResumeActivityLocked(ActivityRecord r) {
        r.state = ActivityState.RESUMED; //1 设置状态
        if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to RESUMED: " + r + " (starting new instance)"
                + " callers=" + Debug.getCallers(5));
        mResumedActivity = r; //2 设置mResumedActivity
        r.task.touchActiveTime(); //3更新task活跃事件
        mRecentTasks.addLocked(r.task); //4 添加到recent中
        completeResumeLocked(r); //5 通知完成resume 
        mStackSupervisor.checkReadyForSleepLocked(); //6 检查休眠
        setLaunchTime(r); //7 更新启动时间
        if (DEBUG_SAVED_STATE) Slog.i(TAG_SAVED_STATE,
                "Launch completed; removing icicle of " + r.icicle);
    }
  • void addRecentActivityLocked(ActivityRecord r) 添加到recent中
  • void awakeFromSleepingLocked()唤醒activity,也就是调用ActivityThread->sleep(false)函数唤醒,同时在mPausingActivity上执行pause,因为之前睡眠的时候没有执行完,只是是它休眠
  • void updateActivityApplicationInfoLocked(ApplicationInfo aInfo) 更新每个activity的ApplicationInfo
  • checkReadyForSleepLocked 函数检查是否可以进入到休眠状态,在非超时的情况应该保证pause activity完成,stoping activity完成,超时则会直接执行sleep函数使activity进入休眠,我们会有机会分析休眠和pause的不同
  • void goToSleep()执行activity的sleep
  • public final Bitmap screenshotActivitiesLocked(ActivityRecord who)截取应用activity缩略图,用于最近任务使用
  • startPausingLocked函数用于pause activity
    1其中参数userLeaving代表要是否要执行Activity的onUserLeaving方法
    2 uiSleeping 表示是否是由于进入睡眠状态引起的pause
    3 resuming表示要resume的activity
    4 dontWait表示不需要等待客户端执行方正回调,直接pause
  final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping,
            ActivityRecord resuming, boolean dontWait) {
         //1如果当前正在pause activity,则不在睡眠状态的华,直接执行completePauseLocked函数完成暂停
        if (mPausingActivity != null) {
            Slog.wtf(TAG, "Going to pause when pause is already pending for " + mPausingActivity
                    + " state=" + mPausingActivity.state);
            if (!mService.isSleepingLocked()) {
                // 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);
            }
        }
        //2 mResumedActivity不存在并且指定要显示的activity也不存在,那么stack上可能不存在要显示的activity,所以执行
        //resumeFocusedStackTopActivityLocked 函数尝试resume activity
        ActivityRecord prev = mResumedActivity;
        if (prev == null) {
            if (resuming == null) {
                Slog.wtf(TAG, "Trying to pause when nothing is resumed");
                mStackSupervisor.resumeFocusedStackTopActivityLocked();
            }
            return false;
        }
        //3 如果这是一个顶级的activity,那么要puase他的子activity
        if (mActivityContainer.mParentActivity == null) {
            // Top level stack, not a child. Look for child stacks.
            mStackSupervisor.pauseChildStacks(prev, userLeaving, uiSleeping, resuming, dontWait);
        }

        if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to PAUSING: " + prev);
        else if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Start pausing: " + prev);
        // 4 更新切换过程中的变量,和activity状态为PAUSING
        mResumedActivity = null;
        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.state = ActivityState.PAUSING;
        prev.task.touchActiveTime();
        clearLaunchTime(prev);
        final ActivityRecord next = mStackSupervisor.topRunningActivityLocked();
        if (mService.mHasRecents
                && (next == null || next.noDisplay || next.task != prev.task || uiSleeping)) {
            prev.mUpdateTaskThumbnailWhenHidden = true;
        }
        stopFullyDrawnTraceIfNeeded();

        mService.updateCpuStats();

        if (prev.app != null && prev.app.thread != null) {
          //5 调用客户端pause方法
            if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Enqueueing pending pause: " + prev);
            try {
                EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
                        prev.userId, System.identityHashCode(prev),
                        prev.shortComponentName);
                mService.updateUsageStats(prev, false);
                prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
                        userLeaving, prev.configChangeFlags, dontWait);
            } catch (Exception e) {
            //6异常清空状态
                // Ignore exception, if process died other code will cleanup.
                Slog.w(TAG, "Exception thrown during pause", e);
                mPausingActivity = null;
                mLastPausedActivity = null;
                mLastNoHistoryActivity = null;
            }
        } else {
         //7 进程不存在清理状态
            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.
        //8 获取lunch 锁,马上要进行resume操作
        if (!uiSleeping && !mService.isSleepingOrShuttingDownLocked()) {
            mStackSupervisor.acquireLaunchWakelock();
        }

        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.
            //9 没有进入睡眠则停止接收input 事件
            if (!uiSleeping) {
                prev.pauseKeyDispatchingLocked();
            } else if (DEBUG_PAUSE) { //睡眠的时候不结束接收input
                 Slog.v(TAG_PAUSE, "Key dispatch not paused for screen off");
            }

            if (dontWait) {
             //10 不需要等待客户端完成,执行completePauseLocked善后
                // If the caller said they don't want to wait for the pause, then complete
                // the pause now.
                completePauseLocked(false, resuming);
                return false;

            } else {
             //11 需要等待客户端完成,发送超时消息,防止客户端太磨蹭
                // Schedule a pause timeout in case the app doesn't respond.
                // We don't give it much time because this directly impacts the
                // responsiveness seen by the user.
                Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
                msg.obj = prev;
                prev.pauseTime = SystemClock.uptimeMillis();
                mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
                if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Waiting for pause to complete...");
                return true;
            }

        } else {
         //12 这里mPausingActivity为空要么是由于activity进程没起来,要么是调用时候异常.  
         // resumeFocusedStackTopActivityLocked因为之前把mResumeActivity搞坏了,这时候重新显示
            // 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.");
            if (resuming == null) {
                mStackSupervisor.resumeFocusedStackTopActivityLocked();
            }
            return false;
        }
    }
  • activityPausedLocked 当客户端执行完成pause回调该函数
final void activityPausedLocked(IBinder token, boolean timeout) {
        if (DEBUG_PAUSE) Slog.v(TAG_PAUSE,
            "Activity paused: token=" + token + ", timeout=" + timeout);
     //1 找到pause的activity
        final ActivityRecord r = isInStackLocked(token);
        if (r != null) {
            //2 移除超时消息
            mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
            if (mPausingActivity == r) { 
            //3 如果正式我们要pause的activity,调用completePauseLocked函数
                if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to PAUSED: " + r
                        + (timeout ? " (due to timeout)" : " (pause complete)"));
                completePauseLocked(true, null);
                return;
            } else {
               // 4 打印log.设置状态,如果需要finish则调用finishCurrentActivityLocked执行finish函数
                EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
                        r.userId, System.identityHashCode(r), r.shortComponentName,
                        mPausingActivity != null
                            ? mPausingActivity.shortComponentName : "(none)");
                if (r.state == ActivityState.PAUSING) {
                    r.state = ActivityState.PAUSED;
                    if (r.finishing) {
                        if (DEBUG_PAUSE) Slog.v(TAG,
                                "Executing finish of failed to pause activity: " + r);
                        finishCurrentActivityLocked(r, FINISH_AFTER_VISIBLE, false);
                    }
                }
            }
        }
        // 5 确保activity可见
        mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
    }
  • stop回调完成,activityStoppedLocked
final void activityStoppedLocked(ActivityRecord r, Bundle icicle,
            PersistableBundle persistentState, CharSequence description) {
        if (r.state != ActivityState.STOPPING) { //1 移除该activity超时消息
            Slog.i(TAG, "Activity reported stop, but no longer stopping: " + r);
            mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
            return;
        }
        //2 保存持久华状态
        if (persistentState != null) {
            r.persistentState = persistentState;
            mService.notifyTaskPersisterLocked(r.task, false);
        }
        if (DEBUG_SAVED_STATE) Slog.i(TAG_SAVED_STATE, "Saving icicle of " + r + ": " + icicle);
        //3 更新缩略图
        if (icicle != null) {
            // If icicle is null, this is happening due to a timeout, so we
            // haven't really saved the state.
            r.icicle = icicle;
            r.haveState = true;
            r.launchCount = 0;
            r.updateThumbnailLocked(null, description);
        }
        //4更新stop状态,通知wms
        if (!r.stopped) {
            if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to STOPPED: " + r + " (stop complete)");
            mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
            r.stopped = true;
            r.state = ActivityState.STOPPED;

            mWindowManager.notifyAppStopped(r.appToken);

            if (getVisibleBehindActivity() == r) {
                mStackSupervisor.requestVisibleBehindLocked(r, false);
            }
            if (r.finishing) {
                r.clearOptionsLocked();
            } else {
               // 5 延迟启动知道paused完成的清空,先销毁,在会需栈上的activity
                if (r.deferRelaunchUntilPaused) {
                    destroyActivityLocked(r, true, "stop-config");
                    mStackSupervisor.resumeFocusedStackTopActivityLocked();
                } else {
                    mStackSupervisor.updatePreviousProcessLocked(r);
                }
            }
        }
    }
  • 完成pause操作

private void completePauseLocked(boolean resumeNext, ActivityRecord resuming) {
        ActivityRecord prev = mPausingActivity;
        if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Complete pause: " + prev);

        if (prev != null) { 
           //1 pause 的activity不为空则设置状态,如果需要finish则调用finishCurrentActivityLocked函数
            final boolean wasStopping = prev.state == ActivityState.STOPPING;
            prev.state = ActivityState.PAUSED;
            if (prev.finishing) {
                if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Executing finish of activity: " + prev);
                prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE, false);
            } else if (prev.app != null) {
             //2 pause的activity进程存在
                if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Enqueue pending stop if needed: " + prev
                        + " wasStopping=" + wasStopping + " visible=" + prev.visible);
                if (mStackSupervisor.mWaitingVisibleActivities.remove(prev)) {
                    if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(TAG_PAUSE,
                            "Complete pause, no longer waiting: " + prev);
                }
                //3 延迟启动的清空,这里已经可以启动了,启动它
                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);
                    relaunchActivityLocked(prev, prev.configChangeFlags, false,
                            prev.preserveWindowOnDeferredRelaunch);
                //4 之前就是stopping状态的,直接设置状态STOPPING
                } 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.state = ActivityState.STOPPING;
                //5 如果已经不可见了或者睡眠了则添加到stopping集合中统一处理
                } else if ((!prev.visible && !hasVisibleBehindActivity())
                        || mService.isSleepingOrShuttingDownLocked()) {
                    // If we were visible then resumeTopActivities will release resources before
                    // stopping.
                    addToStopping(prev, true /* immediate */);
                }
            } 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) { //6 结束freezing 状态
                prev.stopFreezingScreenLocked(true /*force*/);
            }
            mPausingActivity = null;
        }

        if (resumeNext) { // 7 需要显示下一个activity
            final ActivityStack topStack = mStackSupervisor.getFocusedStack();
            if (!mService.isSleepingOrShuttingDownLocked()) {
            //8 没有进入睡眠状态,则恢复focused stack上的actvity
                mStackSupervisor.resumeFocusedStackTopActivityLocked(topStack, prev, null);
            } else {
               //9 睡眠状态不使用prev状态,在某个stack恢复activity
                mStackSupervisor.checkReadyForSleepLocked();
                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();
                }
            }
        }
     //10 更新电池统计信息
        if (prev != null) { //10 恢复接收key
            prev.resumeKeyDispatchingLocked();

            if (prev.app != null && prev.cpuTimeAtResume > 0
                    && mService.mBatteryStatsService.isOnBattery()) {
                long diff = mService.mProcessCpuTracker.getCpuTimeForPid(prev.app.pid)
                        - prev.cpuTimeAtResume;
                if (diff > 0) {
                    BatteryStatsImpl bsi = mService.mBatteryStatsService.getActiveStatistics();
                    synchronized (bsi) {
                        BatteryStatsImpl.Uid.Proc ps =
                                bsi.getProcessStatsLocked(prev.info.applicationInfo.uid,
                                        prev.info.packageName);
                        if (ps != null) {
                            ps.addForegroundTimeLocked(diff);
                        }
                    }
                }
            }
            prev.cpuTimeAtResume = 0; // reset it
        }
  //11 通知task可见
        // Notify when the task stack has changed, but only if visibilities changed (not just
        // focus). Also if there is an active pinned stack - we always want to notify it about
        // task stack changes, because its positioning may depend on it.
        if (mStackSupervisor.mAppVisibilitiesChangedSinceLastPause
                || mService.mStackSupervisor.getStack(PINNED_STACK_ID) != null) {
            mService.notifyTaskStackChangedLocked();
            mStackSupervisor.mAppVisibilitiesChangedSinceLastPause = false;
        }

        mStackSupervisor.ensureActivitiesVisibleLocked(resuming, 0, !PRESERVE_WINDOWS);
    }
  • addToStopping函数将要暂停的activity放到集合中,方便批量处理
  private void addToStopping(ActivityRecord r, boolean immediate) {
        //1 添加到集合
        if (!mStackSupervisor.mStoppingActivities.contains(r)) {
            mStackSupervisor.mStoppingActivities.add(r);
        }

        // If we already have a few activities waiting to stop, then give up
        // on things going idle and start clearing them out. Or if r is the
        // last of activity of the last task the stack will be empty and must
        // be cleared immediately.
        //2 要stop的activity超出了最大限制 或者 activity是stack中最后一个activity,设置forceIdle为真
        boolean forceIdle = mStackSupervisor.mStoppingActivities.size() > MAX_STOPPING_TO_FORCE
                || (r.frontOfTask && mTaskHistory.size() <= 1);

        if (immediate || forceIdle) {
        //3 进入idle状态,进行清理
            if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Scheduling idle now: forceIdle="
                    + forceIdle + "immediate=" + immediate);
            mStackSupervisor.scheduleIdleLocked();
        } else {
            //4 检查睡眠状态
            mStackSupervisor.checkReadyForSleepLocked();
        }
    }

addToStopping这个函数要解释一下,对于3,4状态,一般finish一个activity要进入状态4,由于其他activity启动导致的stop则走状态3,状态四一般会收集一些activity,直到睡眠再去清理

  • completeResumeLocked完成resume时候的操作
private void completeResumeLocked(ActivityRecord next) {
        next.visible = true;
        next.idle = false;
        next.results = null;
        next.newIntents = null;
        next.stopped = false;

        if (next.isHomeActivity()) {
        //1 更新home process
            ProcessRecord app = next.task.mActivities.get(0).app;
            if (app != null && app != mService.mHomeProcess) {
                mService.mHomeProcess = app;
            }
        }

        if (next.nowVisible) { // 2 通知等待启动的线程,通知keygurd service activity已经开始绘制
            // We won't get a call to reportActivityVisibleLocked() so dismiss lockscreen now.
            mStackSupervisor.reportActivityVisibleLocked(next);
            mStackSupervisor.notifyActivityDrawnForKeyguard();
        }
        // 3 发送一个超时的消息,用于善后处理
        // schedule an idle timeout in case the app doesn't do it for us.
        mStackSupervisor.scheduleIdleTimeoutLocked(next);
        //4 上报activity可见,用于执行动画
        mStackSupervisor.reportResumedActivityLocked(next);
        //5 恢复接收input key
        next.resumeKeyDispatchingLocked();
        mNoAnimActivities.clear();

        // Mark the point when the activity is resuming
        // TODO: To be more accurate, the mark should be before the onCreate,
        //       not after the onResume. But for subsequent starts, onResume is fine.
        //6 更新cpu时间
        if (next.app != null) {
            next.cpuTimeAtResume = mService.mProcessCpuTracker.getCpuTimeForPid(next.app.pid);
        } else {
            next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process
        }

        next.returningOptions = null;
        //7 更新Visible Behind Activity
        if (getVisibleBehindActivity() == next) {
            // When resuming an activity, require it to call requestVisibleBehind() again.
            setVisibleBehindActivity(null);
        }
    }
  • 设置可见
private void setVisible(ActivityRecord r, boolean visible) {
        r.visible = visible;  //1 设置window 需要可见
        if (!visible && r.mUpdateTaskThumbnailWhenHidden) {
            //2 如果不可见并且需要更新缩略图,更新
            r.updateThumbnailLocked(r.task.stack.screenshotActivitiesLocked(r), null);
            r.mUpdateTaskThumbnailWhenHidden = false;
        }
        //3 同步给wms
        mWindowManager.setAppVisibility(r.appToken, visible);
        final ArrayList<ActivityContainer> containers = r.mChildContainers;
        for (int containerNdx = containers.size() - 1; containerNdx >= 0; --containerNdx) {
        //4 设置子activity可见性
            ActivityContainer container = containers.get(containerNdx);
            container.setVisible(visible);
        }
        //5 发生app可见行变化,用于通知ams task stack变化
        mStackSupervisor.mAppVisibilitiesChangedSinceLastPause = true;
    }
  • ActivityRecord findNextTranslucentActivity(ActivityRecord r)  找到给定activity上面的一个全屏的activity
  • 获取下一个焦点的stack ,从上往下找
  • private boolean hasFullscreenTask() 全屏task
  • private boolean isStackTranslucent(ActivityRecord starting, int stackBehindId) 判断stack是否是半透明的,也就是不包含全屏的activity,注意参数stackBehindId表示要求的后面的stack类型
  • int getStackVisibilityLocked(ActivityRecord starting) 返回stack的可见状态
int getStackVisibilityLocked(ActivityRecord starting) {
        if (!isAttached()) {//1 没有attach到display,直接返回不可见
            return STACK_INVISIBLE;
        }
        //2 如果是焦点stack或者最前面的stack直接返回可见
        if (mStackSupervisor.isFrontStack(this) || mStackSupervisor.isFocusedStack(this)) {
            return STACK_VISIBLE;
        }

        final int stackIndex = mStacks.indexOf(this);
        //3 如果stack在最上面但是不是front stack,可能不是top level的stack,则返回不可见
        if (stackIndex == mStacks.size() - 1) {
            Slog.wtf(TAG,
                    "Stack=" + this + " isn't front stack but is at the top of the stack list");
            return STACK_INVISIBLE;
        }

        final ActivityStack focusedStack = mStackSupervisor.getFocusedStack();
        final int focusedStackId = focusedStack.mStackId;
     //4 full screen stack包含后面可见的activity,并且前面是HOME stack,返回STACK_VISIBLE_ACTIVITY_BEHIND
        if (mStackId == FULLSCREEN_WORKSPACE_STACK_ID
                && hasVisibleBehindActivity() && focusedStackId == HOME_STACK_ID
                && !focusedStack.topActivity().fullscreen) {
            // The fullscreen stack should be visible if it has a visible behind activity behind
            // the home stack that is translucent.
            return STACK_VISIBLE_ACTIVITY_BEHIND;
        }
     //2 如果焦点stack的top task可以进入dock stack,或者这个task是Home task则dock stack可见,否则不可见
     //也就是说焦点stack上的top task不能进入dock stack也不是home stack(home stack是半透明的)则不可见
        if (mStackId == DOCKED_STACK_ID) {
            // Docked stack is always visible, except in the case where the top running activity
            // task in the focus stack doesn't support any form of resizing but we show it for the
            // home task even though it's not resizable.
            final ActivityRecord r = focusedStack.topRunningActivityLocked();
            final TaskRecord task = r != null ? r.task : null;
            return task == null || task.canGoInDockedStack() || task.isHomeTask() ? STACK_VISIBLE
                    : STACK_INVISIBLE;
        }

        // Find the first stack behind focused stack that actually got something visible.
        int stackBehindFocusedIndex = mStacks.indexOf(focusedStack) - 1;
        while (stackBehindFocusedIndex >= 0 &&
                mStacks.get(stackBehindFocusedIndex).topRunningActivityLocked() == null) {
            stackBehindFocusedIndex--;
        }
        //3 焦点stack 后面的dock stack和pinned stack是可见的(之前排除了dock不可见的情况)
        if ((focusedStackId == DOCKED_STACK_ID || focusedStackId == PINNED_STACK_ID)
                && stackIndex == stackBehindFocusedIndex) {
            // Stacks directly behind the docked or pinned stack are always visible.
            return STACK_VISIBLE;
        }

        final int stackBehindFocusedId = (stackBehindFocusedIndex >= 0)
                ? mStacks.get(stackBehindFocusedIndex).mStackId : INVALID_STACK_ID;

        if (focusedStackId == FULLSCREEN_WORKSPACE_STACK_ID
                && focusedStack.isStackTranslucent(starting, stackBehindFocusedId)) {
            // Stacks behind the fullscreen stack with a translucent activity are always
            // visible so they can act as a backdrop to the translucent activity.
            // For example, dialog activities
            //4 焦点stack不完全遮挡则,并且是焦点stack下面的stack,返回可见
            if (stackIndex == stackBehindFocusedIndex) {
                return STACK_VISIBLE;
            }
            //5 焦点stack没有完全遮挡,dock stack 和 pinned stack后面的stack也是可见的
            if (stackBehindFocusedIndex >= 0) {
                if ((stackBehindFocusedId == DOCKED_STACK_ID
                        || stackBehindFocusedId == PINNED_STACK_ID)
                        && stackIndex == (stackBehindFocusedIndex - 1)) {
                    // The stack behind the docked or pinned stack is also visible so we can have a
                    // complete backdrop to the translucent activity when the docked stack is up.
                    return STACK_VISIBLE;
                }
            }
        }
        //6 其他情况的静态stack不可见
        if (StackId.isStaticStack(mStackId)) {
            // Visibility of any static stack should have been determined by the conditions above.
            return STACK_INVISIBLE;
        }
     
        for (int i = stackIndex + 1; i < mStacks.size(); i++) {
            final ActivityStack stack = mStacks.get(i);

            if (!stack.mFullscreen && !stack.hasFullscreenTask()) {
                continue;
            }
            //7 动态stack不允许在后台显示,则返回不可见
            if (!StackId.isDynamicStacksVisibleBehindAllowed(stack.mStackId)) {
                // These stacks can't have any dynamic stacks visible behind them.
                return STACK_INVISIBLE;
            }
            //9 完全遮挡则后面的都不可见
            if (!stack.isStackTranslucent(starting, INVALID_STACK_ID)) {
                return STACK_INVISIBLE;
            }
        }
        //9 返回可见
        return STACK_VISIBLE;
    }
  • inal int rankTaskLayers(int baseLayer) 更新layer runk ,从baseLayer叠加,计算adj时候使用

  • ensureActivitiesVisibleLocked 确保每一个可见的activity都被用户看见

** Return true if the input activity should be made visible */
    private boolean shouldBeVisible(ActivityRecord r, boolean behindTranslucentActivity,
            boolean stackVisibleBehind, ActivityRecord visibleBehind,
            boolean behindFullscreenActivity) {

        if (!okToShowLocked(r)) { //1 user下的activity不能显示返回false
            return false;
        }

        // mLaunchingBehind: Activities launching behind are at the back of the task stack
        // but must be drawn initially for the animation as though they were visible.
        //2 activity在后台但是可以被看到
        final boolean activityVisibleBehind =
                (behindTranslucentActivity || stackVisibleBehind) && visibleBehind == r;

        //3 activity看到
        boolean isVisible =
                !behindFullscreenActivity || r.mLaunchTaskBehind || activityVisibleBehind;

        //4 Leanback的处理
        if (mService.mSupportsLeanbackOnly && isVisible && r.isRecentsActivity()) {
            // On devices that support leanback only (Android TV), Recents activity can only be
            // visible if the home stack is the focused stack or we are in split-screen mode.
            isVisible = mStackSupervisor.getStack(DOCKED_STACK_ID) != null
                    || mStackSupervisor.isFocusedStack(this);
        }
        //5 返回是否可见
        return isVisible;
    }
 private boolean makeVisibleAndRestartIfNeeded(ActivityRecord starting, int configChanges,
            boolean isTop, boolean andResume, ActivityRecord r) {
        // We need to make sure the app is running if it's the top, or it is just made visible from
        // invisible. If the app is already visible, it must have died while it was visible. In this
        // case, we'll show the dead window but will not restart the app. Otherwise we could end up
        // thrashing.
        //1 栈顶activity或者activity从不可见变为可见的过程,需要重新启动
        if (isTop || !r.visible) {
            // This activity needs to be visible, but isn't even running...
            // get it started and resume if no other stack in this stack is resumed.
            if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "Start and freeze screen for " + r);
            //2 冻结窗口
            if (r != starting) {
                r.startFreezingScreenLocked(r.app, configChanges);
            }
            //3 设置可见
            if (!r.visible || r.mLaunchTaskBehind) {
                if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "Starting and making visible: " + r);
                setVisible(r, true);
            }
            //4 启动activity
            if (r != starting) {
                mStackSupervisor.startSpecificActivityLocked(r, andResume, false);
                return true;
            }
        }
        return false;
    }


/**
     * Make sure that all activities that need to be visible (that is, they
     * currently can be seen by the user) actually are.
     */
    final void ensureActivitiesVisibleLocked(ActivityRecord starting, int configChanges,
            boolean preserveWindows) {
        ActivityRecord top = topRunningActivityLocked();
        if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "ensureActivitiesVisible behind " + top
                + " configChanges=0x" + Integer.toHexString(configChanges));
        //1 栈顶上有可以正常显示的activity,mTranslucentActivityWaiting不再是顶部activity,做一些处理,
        //mTranslucentActivityWaiting主要用于滑动关闭activity的feature打开后滑动过程中变半透明的情况
        if (top != null) {
            checkTranslucentActivityWaiting(top);
        }

        // If the top activity is not fullscreen, then we need to
        // make sure any activities under it are now visible.
        boolean aboveTop = top != null;
        final int stackVisibility = getStackVisibilityLocked(starting);
        final boolean stackInvisible = stackVisibility != STACK_VISIBLE;
        final boolean stackVisibleBehind = stackVisibility == STACK_VISIBLE_ACTIVITY_BEHIND;
        boolean behindFullscreenActivity = stackInvisible;
        boolean resumeNextActivity = mStackSupervisor.isFocusedStack(this)
                && (isInStackLocked(starting) == null);
        boolean behindTranslucentActivity = false;
        final ActivityRecord visibleBehind = getVisibleBehindActivity();
        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
            final TaskRecord task = mTaskHistory.get(taskNdx);
            final ArrayList<ActivityRecord> activities = task.mActivities;
            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
            //2 遍历activity
                final ActivityRecord r = activities.get(activityNdx);
                if (r.finishing) {
                //3 关闭的如果startPause中要求截图,则截图,下一轮循环
                    // Normally the screenshot will be taken in makeInvisible(). When an activity
                    // is finishing, we no longer change its visibility, but we still need to take
                    // the screenshots if startPausingLocked decided it should be taken.
                    if (r.mUpdateTaskThumbnailWhenHidden) {
                        r.updateThumbnailLocked(screenshotActivitiesLocked(r), null);
                        r.mUpdateTaskThumbnailWhenHidden = false;
                    }
                    continue;
                }
                //4 从top running activity开始处理
                final boolean isTop = r == top;
                if (aboveTop && !isTop) {
                    continue;
                }
                aboveTop = false;

                if (shouldBeVisible(r, behindTranslucentActivity, stackVisibleBehind,
                        visibleBehind, behindFullscreenActivity)) {
                    if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "Make visible? " + r
                            + " finishing=" + r.finishing + " state=" + r.state);
                    // First: if this is not the current activity being started, make
                    // sure it matches the current configuration.
                    //5 更新configure
                    if (r != starting) {
                        ensureActivityConfigurationLocked(r, 0, preserveWindows);
                    }

                    if (r.app == null || r.app.thread == null) {
                        //6如果进程还存在,确保启动
                        if (makeVisibleAndRestartIfNeeded(starting, configChanges, isTop,
                                resumeNextActivity, r)) {
                            if (activityNdx >= activities.size()) {
                                // Record may be removed if its process needs to restart.
                                activityNdx = activities.size() - 1;
                            } else {
                                resumeNextActivity = false;
                            }
                        }
                    } else if (r.visible) {
                        // If this activity is already visible, then there is nothing to do here.
                        if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY,
                                "Skipping: already visible at " + r);

                        if (handleAlreadyVisible(r)) {
                            resumeNextActivity = false;
                        }
                    } else {
                        makeVisibleIfNeeded(starting, r);
                    }
                    // Aggregate current change flags.
                    configChanges |= r.configChangeFlags;
                    behindFullscreenActivity = updateBehindFullscreen(stackInvisible,
                            behindFullscreenActivity, task, r);
                    if (behindFullscreenActivity && !r.fullscreen) {
                        behindTranslucentActivity = true;
                    }
                } else {
                    if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "Make invisible? " + r
                            + " finishing=" + r.finishing + " state=" + r.state + " stackInvisible="
                            + stackInvisible + " behindFullscreenActivity="
                            + behindFullscreenActivity + " mLaunchTaskBehind="
                            + r.mLaunchTaskBehind);
                    makeInvisible(r, visibleBehind);
                }
            }
            if (mStackId == FREEFORM_WORKSPACE_STACK_ID) {
                // The visibility of tasks and the activities they contain in freeform stack are
                // determined individually unlike other stacks where the visibility or fullscreen
                // status of an activity in a previous task affects other.
                behindFullscreenActivity = stackVisibility == STACK_INVISIBLE;
            } else if (mStackId == HOME_STACK_ID) {
                if (task.isHomeTask()) {
                    if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "Home task: at " + task
                            + " stackInvisible=" + stackInvisible
                            + " behindFullscreenActivity=" + behindFullscreenActivity);
                    // No other task in the home stack should be visible behind the home activity.
                    // Home activities is usually a translucent activity with the wallpaper behind
                    // them. However, when they don't have the wallpaper behind them, we want to
                    // show activities in the next application stack behind them vs. another
                    // task in the home stack like recents.
                    behindFullscreenActivity = true;
                } else if (task.isRecentsTask()
                        && task.getTaskToReturnTo() == APPLICATION_ACTIVITY_TYPE) {
                    if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY,
                            "Recents task returning to app: at " + task
                                    + " stackInvisible=" + stackInvisible
                                    + " behindFullscreenActivity=" + behindFullscreenActivity);
                    // We don't want any other tasks in the home stack visible if the recents
                    // activity is going to be returning to an application activity type.
                    // We do this to preserve the visible order the user used to get into the
                    // recents activity. The recents activity is normally translucent and if it
                    // doesn't have the wallpaper behind it the next activity in the home stack
                    // shouldn't be visible when the home stack is brought to the front to display
                    // the recents activity from an app.
                    behindFullscreenActivity = true;
                }

            }
        }

        if (mTranslucentActivityWaiting != null &&
                mUndrawnActivitiesBelowTopTranslucent.isEmpty()) {
            // Nothing is getting drawn or everything was already visible, don't wait for timeout.
            notifyActivityDrawnLocked(null);
        }
    }
  • makeInvisible 函数使atcivity不可见
  private void makeInvisible(ActivityRecord r, ActivityRecord visibleBehind) {
        if (!r.visible) { //1 本身就不可见直接返回
            if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "Already invisible: " + r);
            return;
        }
        // Now for any activities that aren't visible to the user, make sure they no longer are
        // keeping the screen frozen.
        if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "Making invisible: " + r + " " + r.state);
        try {
            //2 设置不可见
            setVisible(r, false);
            switch (r.state) {
                case STOPPING:
                case STOPPED:
                    if (r.app != null && r.app.thread != null) {
                        if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY,
                                "Scheduling invisibility: " + r);
                        //3通知客户端不可见,其实是通知客户端执行stop
                        r.app.thread.scheduleWindowVisibility(r.appToken, false);
                    }
                    break;

                case INITIALIZING:
                case RESUMED:
                case PAUSING:
                case PAUSED:
                    // This case created for transitioning activities from
                    // translucent to opaque {@link Activity#convertToOpaque}.
                    if (visibleBehind == r) {
                        releaseBackgroundResources(r);
                    } else {
                        addToStopping(r, true /* immediate */);
                    }
                    break;

                default:
                    break;
            }
        } catch (Exception e) {
            // Just skip on any failure; we'll make it visible when it next restarts.
            Slog.w(TAG, "Exception thrown making hidden: " + r.intent.getComponent(), e);
        }
    }
  • makeVisibleIfNeeded确保可见,确保在启动activity后面的activity可见
   private void makeVisibleIfNeeded(ActivityRecord starting, ActivityRecord r) {

        // This activity is not currently visible, but is running. Tell it to become visible.
        if (r.state == ActivityState.RESUMED || r == starting) {
            if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY,
                    "Not making visible, r=" + r + " state=" + r.state + " starting=" + starting);
            return;
        }

        // If this activity is paused, tell it to now show its window.
        if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY,
                "Making visible and scheduling visibility: " + r);
        try {
            if (mTranslucentActivityWaiting != null) {
                r.updateOptionsLocked(r.returningOptions);
                mUndrawnActivitiesBelowTopTranslucent.add(r);
            }
            setVisible(r, true);
            r.sleeping = false;
            r.app.pendingUiClean = true;
            r.app.thread.scheduleWindowVisibility(r.appToken, true);
            // The activity may be waiting for stop, but that is no longer
            // appropriate for it.
            mStackSupervisor.mStoppingActivities.remove(r);
            mStackSupervisor.mGoingToSleepActivities.remove(r);
        } catch (Exception e) {
            // Just skip on any failure; we'll make it
            // visible when it next restarts.
            Slog.w(TAG, "Exception thrown making visibile: " + r.intent.getComponent(), e);
        }
        handleAlreadyVisible(r);
    }
  • 下面是resume系列函数
//注意参数prev和这个函数可以分为两种情况去分析
//1 启动新的activity这个prev就是要启动的activity,我们要显示它
//2 关闭一个activity需要显示后面的activity,这里prev就是要关闭的activity
 boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
        if (mStackSupervisor.inResumeTopActivity) {//1 防止嵌套执行,如果inResumeTopActivity为真直接返回
            // Don't even start recursing.
            return false;
        }

        boolean result = false;
        try {
            //2 设置inResumeTopActivity防止嵌套执行
            // Protect against recursion.
            mStackSupervisor.inResumeTopActivity = true;
            //3 keygurd刚刚关闭,更新睡眠状态
            if (mService.mLockScreenShown == ActivityManagerService.LOCK_SCREEN_LEAVING) {
                mService.mLockScreenShown = ActivityManagerService.LOCK_SCREEN_HIDDEN;
                mService.updateSleepIfNeededLocked();
            }
            //4执行resumeTopActivityInnerLocked
            result = resumeTopActivityInnerLocked(prev, options);
        } finally {
          //5 重置inResumeTopActivity以便可以重新执行resume
            mStackSupervisor.inResumeTopActivity = false;
        }
        return result;
    }

    private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
        if (DEBUG_LOCKSCREEN) mService.logLockScreen("");
        //1 没有启动完成,直接返回
        if (!mService.mBooting && !mService.mBooted) {
            // Not ready yet!
            return false;
        }
        //2 父activity不可见直接返回
        ActivityRecord parent = mActivityContainer.mParentActivity;
        if ((parent != null && parent.state != ActivityState.RESUMED) ||
                !mActivityContainer.isAttachedLocked()) {
            // Do not resume this stack if its parent is not resumed.
            // TODO: If in a loop, make sure that parent stack resumeTopActivity is called 1st.
            return false;
        }
        //3 主要用于移除各个栈上不需要的starting window
        mStackSupervisor.cancelInitializingActivities();
        //4 下一个可以运行的activity
        // Find the first activity that is not finishing.
        final ActivityRecord next = topRunningActivityLocked();

        // Remember how we'll process this pause/resume situation, and ensure
        // that the state is reset however we wind up proceeding.
        //5设置是否执行客户端onUserLeaving函数
        final boolean userLeaving = mStackSupervisor.mUserLeaving;
        mStackSupervisor.mUserLeaving = false;

        final TaskRecord prevTask = prev != null ? prev.task : null;
        if (next == null) { 
            // There are no more activities!
            final String reason = "noMoreActivities";
            final int returnTaskType = prevTask == null || !prevTask.isOverHomeStack()
                    ? HOME_ACTIVITY_TYPE : prevTask.getTaskToReturnTo();
            //6 不是全屏activity计算下一个焦点,尝试恢复新的焦点stack上的activity
            if (!mFullscreen && adjustFocusToNextFocusableStackLocked(returnTaskType, reason)) {
                // Try to move focus to the next visible stack with a running activity if this
                // stack is not covering the entire screen.
                return mStackSupervisor.resumeFocusedStackTopActivityLocked(
                        mStackSupervisor.getFocusedStack(), prev, null);
            }

            // Let's just start up the Launcher...
            ActivityOptions.abort(options);
            if (DEBUG_STATES) Slog.d(TAG_STATES,
                    "resumeTopActivityLocked: No more activities go home");
            if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
            // Only resume home if on home display
            //7 恢复home activity显示,注意6和7恢复是不能完成的,因为是嵌套在resume中的,我想
            //是google新的开发者对这块代码也不能百分百的理解
            return isOnHomeDisplay() &&
                    mStackSupervisor.resumeHomeStackTask(returnTaskType, prev, reason);
        }

        next.delayedResume = false;

        // If the top activity is the resumed one, nothing to do.
        if (mResumedActivity == next && next.state == ActivityState.RESUMED &&
                    mStackSupervisor.allResumedActivitiesComplete()) {
        //9 已经是resume状态乐,不需要做什么. 
            // Make sure we have executed any pending transitions, since there
            // should be nothing left to do at this point.
            mWindowManager.executeAppTransition();
            mNoAnimActivities.clear();
            ActivityOptions.abort(options);
            if (DEBUG_STATES) Slog.d(TAG_STATES,
                    "resumeTopActivityLocked: Top activity resumed " + next);
            if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
            return false;
        }

        final TaskRecord nextTask = next.task;
        if (prevTask != null && prevTask.stack == this &&
                prevTask.isOverHomeStack() && prev.finishing && prev.frontOfTask) {
            //10 prev是正在关闭的activity,并且在桌面上面的task
            if (DEBUG_STACK)  mStackSupervisor.validateTopActivitiesLocked();
            if (prevTask == nextTask) {
                prevTask.setFrontOfTask(); //11 task中还有其他activity,更新fron of task
            } else if (prevTask != topTask()) {
                //12 task中最后一个activity,设置下一个task下面的task为桌面task
                // This task is going away but it was supposed to return to the home stack.
                // Now the task above it has to return to the home task instead.
                final int taskNdx = mTaskHistory.indexOf(prevTask) + 1;
                mTaskHistory.get(taskNdx).setTaskToReturnTo(HOME_ACTIVITY_TYPE);
            } else if (!isOnHomeDisplay()) {
                return false;
            } else if (!isHomeStack()){
                if (DEBUG_STATES) Slog.d(TAG_STATES,
                        "resumeTopActivityLocked: Launching home next");
                final int returnTaskType = prevTask == null || !prevTask.isOverHomeStack() ?
                        HOME_ACTIVITY_TYPE : prevTask.getTaskToReturnTo();
                return isOnHomeDisplay() &&
                        mStackSupervisor.resumeHomeStackTask(returnTaskType, prev, "prevFinished");
            }
        }

        // If we are sleeping, and there is no resumed activity, and the top
        // activity is paused, well that is the state we want.
        if (mService.isSleepingOrShuttingDownLocked()
                && mLastPausedActivity == next
                && mStackSupervisor.allPausedActivitiesComplete()) {
            // Make sure we have executed any pending transitions, since there
            // should be nothing left to do at this point.
            //13 在关机或者进入睡眠状态,并且完成pause这时候不需要再去resume activity
            mWindowManager.executeAppTransition();
            mNoAnimActivities.clear();
            ActivityOptions.abort(options);
            if (DEBUG_STATES) Slog.d(TAG_STATES,
                    "resumeTopActivityLocked: Going to sleep and all paused");
            if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
            return false;
        }

        // Make sure that the user who owns this activity is started.  If not,
        // we will just leave it as is because someone should be bringing
        // another user's activities to the top of the stack.
        //14 user没有启动,直接返回
        if (!mService.mUserController.hasStartedUserState(next.userId)) {
            Slog.w(TAG, "Skipping resume of top activity " + next
                    + ": user " + next.userId + " is stopped");
            if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
            return false;
        }

        // The activity may be waiting for stop, but that is no longer
        // appropriate for it.
        mStackSupervisor.mStoppingActivities.remove(next);
        mStackSupervisor.mGoingToSleepActivities.remove(next);
        next.sleeping = false;
        mStackSupervisor.mWaitingVisibleActivities.remove(next);

        if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "Resuming " + next);

        // If we are currently pausing an activity, then don't do anything until that is done.
        //15 存在activity没有完成的,什么都不用做,完成后自会进入resume流程
        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;
        }

        mStackSupervisor.setLaunchSource(next.info.applicationInfo.uid);

        // We need to start pausing the current activity so the top one can be resumed...
        //FLAG_RESUME_WHILE_PAUSING表示不需要等待前面的activity pause完成在resume activity,设置该值
        //pauseBackStacks和startPausingLocked会返回false
        final boolean dontWaitForPause = (next.info.flags & FLAG_RESUME_WHILE_PAUSING) != 0;
        //16 pause 非焦点stack的activity
        boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving, next, dontWaitForPause);
        if (mResumedActivity != null) {
            if (DEBUG_STATES) Slog.d(TAG_STATES,
                    "resumeTopActivityLocked: Pausing " + mResumedActivity);
            //17 pause resume activity,对于关闭activity显示后面activity的情况这里是进步来的,只有启动
            //新的activity进入这里
            pausing |= startPausingLocked(userLeaving, false, next, dontWaitForPause);
        }
        if (pausing) {
            //18 启动新activity在这里暂时结束,需要mResumeActivity关闭完成才会再次进入
            if (DEBUG_SWITCH || DEBUG_STATES) Slog.v(TAG_STATES,
                    "resumeTopActivityLocked: Skip resume: need to start pausing");
            // At this point we want to put the upcoming activity's process
            // at the top of the LRU list, since we know we will be needing it
            // very soon and it would be a waste to let it get killed if it
            // happens to be sitting towards the end.
            if (next.app != null && next.app.thread != null) {
                mService.updateLruProcessLocked(next.app, true, null);
            }
            if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
            return true;
        } else if (mResumedActivity == next && next.state == ActivityState.RESUMED &&
                mStackSupervisor.allResumedActivitiesComplete()) {
            // It is possible for the activity to be resumed when we paused back stacks above if the
            // next activity doesn't have to wait for pause to complete.
            // So, nothing else to-do except:
            // Make sure we have executed any pending transitions, since there
            // should be nothing left to do at this point.
            //19 next已经resume完成,什么都不做
            mWindowManager.executeAppTransition();
            mNoAnimActivities.clear();
            ActivityOptions.abort(options);
            if (DEBUG_STATES) Slog.d(TAG_STATES,
                    "resumeTopActivityLocked: Top activity resumed (dontWaitForPause) " + next);
            if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
            return true;
        }

        // If the most recent activity was noHistory but was only stopped rather
        // than stopped+finished because the device went to sleep, we need to make
        // sure to finish it as we're making a new activity topmost.
        if (mService.isSleepingLocked() && mLastNoHistoryActivity != null &&
                !mLastNoHistoryActivity.finishing) {
            if (DEBUG_STATES) Slog.d(TAG_STATES,
                    "no-history finish of " + mLastNoHistoryActivity + " on new resume");
            requestFinishActivityLocked(mLastNoHistoryActivity.appToken, Activity.RESULT_CANCELED,
                    null, "resume-no-history", false);
            mLastNoHistoryActivity = null;
        }

        if (prev != null && prev != next) {
            if (!mStackSupervisor.mWaitingVisibleActivities.contains(prev)
                    && next != null && !next.nowVisible) {
                mStackSupervisor.mWaitingVisibleActivities.add(prev);
                //20 添加可见activity表示需要等待新的activity可见,这些activity需要进入到stop状态
                if (DEBUG_SWITCH) Slog.v(TAG_SWITCH,
                        "Resuming top, waiting visible to hide: " + prev);
            } else {
                // The next activity is already visible, so hide the previous
                // activity's windows right now so we can show the new one ASAP.
                // We only do this if the previous is finishing, which should mean
                // it is on top of the one being resumed so hiding it quickly
                // is good.  Otherwise, we want to do the normal route of allowing
                // the resumed activity to be shown so we can decide if the
                // previous should actually be hidden depending on whether the
                // new one is found to be full-screen or not.
                if (prev.finishing) { 
                    mWindowManager.setAppVisibility(prev.appToken, false);
                    if (DEBUG_SWITCH) Slog.v(TAG_SWITCH,
                            "Not waiting for visible to hide: " + prev + ", waitingVisible="
                            + mStackSupervisor.mWaitingVisibleActivities.contains(prev)
                            + ", nowVisible=" + next.nowVisible);
                } else {
                    if (DEBUG_SWITCH) Slog.v(TAG_SWITCH,
                            "Previous already visible but still waiting to hide: " + prev
                            + ", waitingVisible="
                            + mStackSupervisor.mWaitingVisibleActivities.contains(prev)
                            + ", nowVisible=" + next.nowVisible);
                }
            }
        }

        // Launching this app's activity, make sure the app is no longer
        // considered stopped.
        try {
            AppGlobals.getPackageManager().setPackageStoppedState(
                    next.packageName, false, next.userId); /* TODO: Verify if correct userid */
        } catch (RemoteException e1) {
        } catch (IllegalArgumentException e) {
            Slog.w(TAG, "Failed trying to unstop package "
                    + next.packageName + ": " + e);
        }

        // We are starting up the next activity, so tell the window manager
        // that the previous one will be hidden soon.  This way it can know
        // to ignore it when computing the desired screen orientation.
        boolean anim = true;
        //21  动画相关
        if (prev != null) {
            if (prev.finishing) {
                if (DEBUG_TRANSITION) Slog.v(TAG_TRANSITION,
                        "Prepare close transition: prev=" + prev);
                if (mNoAnimActivities.contains(prev)) {
                    anim = false;
                    mWindowManager.prepareAppTransition(TRANSIT_NONE, false);
                } else {
                    mWindowManager.prepareAppTransition(prev.task == next.task
                            ? TRANSIT_ACTIVITY_CLOSE
                            : TRANSIT_TASK_CLOSE, false);
                }
                mWindowManager.setAppVisibility(prev.appToken, false);
            } else {
                if (DEBUG_TRANSITION) Slog.v(TAG_TRANSITION,
                        "Prepare open transition: prev=" + prev);
                if (mNoAnimActivities.contains(next)) {
                    anim = false;
                    mWindowManager.prepareAppTransition(TRANSIT_NONE, false);
                } else {
                    mWindowManager.prepareAppTransition(prev.task == next.task
                            ? TRANSIT_ACTIVITY_OPEN
                            : next.mLaunchTaskBehind
                                    ? TRANSIT_TASK_OPEN_BEHIND
                                    : TRANSIT_TASK_OPEN, false);
                }
            }
        } else {
            if (DEBUG_TRANSITION) Slog.v(TAG_TRANSITION, "Prepare open transition: no previous");
            if (mNoAnimActivities.contains(next)) {
                anim = false;
                mWindowManager.prepareAppTransition(TRANSIT_NONE, false);
            } else {
                mWindowManager.prepareAppTransition(TRANSIT_ACTIVITY_OPEN, false);
            }
        }

        Bundle resumeAnimOptions = null;
        if (anim) {
            ActivityOptions opts = next.getOptionsForTargetActivityLocked();
            if (opts != null) {
                resumeAnimOptions = opts.toBundle();
            }
            next.applyOptionsLocked();
        } else {
            next.clearOptionsLocked();
        }

        ActivityStack lastStack = mStackSupervisor.getLastStack();
        if (next.app != null && next.app.thread != null) {
            if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "Resume running: " + next
                    + " stopped=" + next.stopped + " visible=" + next.visible);

            // 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.mFullscreen
                    || (lastStack.mLastPausedActivity != null
                    && !lastStack.mLastPausedActivity.fullscreen));

            //22 设置可见
            // This activity is now becoming visible.
            if (!next.visible || next.stopped || lastActivityTranslucent) {
                mWindowManager.setAppVisibility(next.appToken, true);
            }

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

            ActivityRecord lastResumedActivity =
                    lastStack == null ? null :lastStack.mResumedActivity;
            ActivityState lastState = next.state;

            mService.updateCpuStats();

            if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to RESUMED: " + next + " (in existing)");
            next.state = ActivityState.RESUMED;
            mResumedActivity = next;
            next.task.touchActiveTime();
            mRecentTasks.addLocked(next.task);
            mService.updateLruProcessLocked(next.app, true, null);
            updateLRUListLocked(next);
            mService.updateOomAdjLocked();

            // Have the window manager re-evaluate the orientation of
            // the screen based on the new activity order.
            boolean notUpdated = true;
            if (mStackSupervisor.isFocusedStack(this)) {
                Configuration config = mWindowManager.updateOrientationFromAppTokens(
                        mService.mConfiguration,
                        next.mayFreezeScreenLocked(next.app) ? next.appToken : null);
                if (config != null) {
                    next.frozenBeforeDestroy = true;
                }
                notUpdated = !mService.updateConfigurationLocked(config, next, false);
            }

            if (notUpdated) {
                // The configuration update wasn't able to keep the existing
                // instance of the activity, and instead started a new one.
                // We should be all done, but let's just make sure our activity
                // is still at the top and schedule another run if something
                // weird happened.
                ActivityRecord nextNext = topRunningActivityLocked();
                if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG_STATES,
                        "Activity config changed during resume: " + next
                        + ", new next: " + nextNext);
                if (nextNext != next) {
                    // Do over!
                    mStackSupervisor.scheduleResumeTopActivities();
                }
                if (mStackSupervisor.reportResumedActivityLocked(next)) {
                    mNoAnimActivities.clear();
                    if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
                    return true;
                }
                if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
                return false;
            }

            try {
                // Deliver all pending results.
                ArrayList<ResultInfo> a = next.results;
                if (a != null) {
                    final int N = a.size();
                    if (!next.finishing && N > 0) {
                        if (DEBUG_RESULTS) Slog.v(TAG_RESULTS,
                                "Delivering results to " + next + ": " + a);
                        next.app.thread.scheduleSendResult(next.appToken, a);
                    }
                }

                boolean allowSavedSurface = true;
                if (next.newIntents != null) {
                    // Restrict saved surface to launcher start, or there is no intent at all
                    // (eg. task being brought to front). If the intent is something else,
                    // likely the app is going to show some specific page or view, instead of
                    // what's left last time.
                    for (int i = next.newIntents.size() - 1; i >= 0; i--) {
                        final Intent intent = next.newIntents.get(i);
                        if (intent != null && !ActivityRecord.isMainIntent(intent)) {
                            allowSavedSurface = false;
                            break;
                        }
                    }
                    next.app.thread.scheduleNewIntent(
                            next.newIntents, next.appToken, false /* andPause */);
                }

                // Well the app will no longer be stopped.
                // Clear app token stopped state in window manager if needed.
                mWindowManager.notifyAppResumed(next.appToken, next.stopped, allowSavedSurface);

                EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY, next.userId,
                        System.identityHashCode(next), next.task.taskId, next.shortComponentName);

                next.sleeping = false;
                mService.showUnsupportedZoomDialogIfNeededLocked(next);
                mService.showAskCompatModeDialogLocked(next);
                next.app.pendingUiClean = true;
                next.app.forceProcessStateUpTo(mService.mTopProcessState);
                next.clearOptionsLocked();
                //22 进程已经启动 resume activity
                next.app.thread.scheduleResumeActivity(next.appToken, next.app.repProcState,
                        mService.isNextTransitionForward(), resumeAnimOptions);

                mStackSupervisor.checkReadyForSleepLocked();

                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.state = lastState;
                if (lastStack != null) {
                    lastStack.mResumedActivity = lastResumedActivity;
                }
                Slog.i(TAG, "Restarting because process died: " + next);
                if (!next.hasBeenLaunched) {
                    next.hasBeenLaunched = true;
                } else  if (SHOW_APP_STARTING_PREVIEW && lastStack != null &&
                        mStackSupervisor.isFrontStack(lastStack)) {
                    next.showStartingWindow(null, true);
                }
                mStackSupervisor.startSpecificActivityLocked(next, true, false);
                if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
                return true;
            }

            // From this point on, if something goes wrong there is no way
            // to recover the activity.
            try {
                //23 完成启动
                completeResumeLocked(next);
            } 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);
                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, true);
                }
                if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "Restarting: " + next);
            }
            if (DEBUG_STATES) Slog.d(TAG_STATES, "resumeTopActivityLocked: Restarting " + next);
            //23启动进程的流程
            mStackSupervisor.startSpecificActivityLocked(next, true, true);
        }

        if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
        return true;
    }
  • 计算下一个焦点stack
  private boolean adjustFocusToNextFocusableStackLocked(int taskToReturnTo, String reason) {
        final ActivityStack stack = getNextFocusableStackLocked();
        final String myReason = reason + " adjustFocusToNextFocusableStack";
        if (stack == null) {
            return false;
        }

        final ActivityRecord top = stack.topRunningActivityLocked();

        if (stack.isHomeStack() && (top == null || !top.visible)) {
            // If we will be focusing on the home stack next and its current top activity isn't
            // visible, then use the task return to value to determine the home task to display next.
            return mStackSupervisor.moveHomeStackTaskToTop(taskToReturnTo, reason);
        }
        return mService.setFocusedActivityLocked(top, myReason);
    }

总结下需要追踪的流程
1 启动普通的activity
2 休眠
3 idle流程
4 分屏幕 拖拽
5 config变化
6 requestBehind
7 activity崩溃
8 lock task
9 mTranslucentActivityWaiting 这个

猜你喜欢

转载自blog.csdn.net/woai110120130/article/details/80033501