IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 移动开发 -> 解析Activity启动-生命周期角度 -> 正文阅读

[移动开发]解析Activity启动-生命周期角度

解析Activity启动-生命周期角度

  • 书接上回,在 AMS侧解析Activity启动 篇章中,我们大致梳理了 Activity 启动过程中涉及到堆栈的整体流程,本篇再让我们从 Activity 生命周期的角度来梳理整个流程

  • 顺着上一篇 解析Activity启动-堆栈篇 的流程,在启动Activity时,会在 resumeTopActivityInnerLocked() 函数中调用 startPausingLocked() 函数对发起者Activity触发 Pause 动作,那么我们就按照启动顺序,进行逐一分析

① onPause

  • 在前一篇文章中,我们也有涉及 startPausingLocked() 函数的分析,但是并没有特别细致和深入,那么在此处,我们顺着该函数,较为细致的解析一下

1.1 resumeTopActivityInnerLocked()

frameworks\base\services\core\java\com\android\server\am\ActivityStack.java

@GuardedBy("mService")
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
    ...
    // 如果当前Stack中的mResumedActivity不为空,也就是当前处于 resume 状态的Activity不为空,命中if
   //去异步 pause mResumedActivity
    if (mResumedActivity != null) {
        if (DEBUG_STATES)
            Slog.d(TAG_STATES,
                   "resumeTopActivityLocked: Pausing " + mResumedActivity);
        // pausing当前Stack的mResumedActivity,此处返回值也是false,就是这里需要先pause再去resume
        pausing |= startPausingLocked(userLeaving, false, next, false);
    }
    ...
}
  • 首先是调用起点,剔除与Pause流程无关的代码;可以看到,只有在对应 stack中存在 mResumedActivity 时,才会去触发进行Pause流程,很好理解,如果对应stack中并不存在Resume状态的Activity,那也就不存在Activity需要进行Pause,此处也重点关注一下传入的参数

1.2 startPausingLocked()

frameworks\base\services\core\java\com\android\server\am\ActivityStack.java

    // pausing当前Stack中的mResumedActivity对象,只有在该mResumedActivity存在,
    // 并且异步调用finish Activity的才会返回true
    final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping,
            ActivityRecord resuming, boolean pauseImmediately) {
        // 判断当前Stack的mPausingActivity是否为空,如果不为空,代表中有正在进行pause的Activity,
        //且对应display不是sleep状态,那么就完成mPausingActivity的pause流程,
        //并将 mPausingActivity置空
        if (mPausingActivity != null) {
            // 如果当前display不处于Sleeping状态,命中if
            // 完成mPausingActivity的Pause,其实就是设置相关的标志位,如state等,
            //并且将mPausingActivity置空
            if (!shouldSleepActivities()) {
                completePauseLocked(false, resuming);
            }
        }
        // 拿到当前Stack的mResumedActivity
        ActivityRecord prev = mResumedActivity;

        // mResumedActivity等于空,直接返回,就不需要pause了
        if (prev == null) {
			...
            return false;
        }

        // mResumedActivity就是需要resume的mStartActivity,直接返回,也不用pause了
        if (prev == resuming) {
            return false;
        }

        // 将当前resumed的Activity赋值给mPausingActivity和mLastPausedActivity
        //也就是移交状态,用这两个变量记录prev,代表他开始进入pause流程
        mPausingActivity = prev;
        mLastPausedActivity = prev;
        // 如果当前resumed的Activity设置了FLAG_ACTIVITY_NO_HISTORY或者FLAG_NO_HISTORY,那么就将
        // 当前resumed的Activity保存到mLastNoHistoryActivity中
        //代表该Activity不需要被保存在historyActivity列表中
        mLastNoHistoryActivity = (prev.intent.getFlags() & Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
                || (prev.info.flags & ActivityInfo.FLAG_NO_HISTORY) != 0 ? prev : null;
        // 设置当前resumed的Activity的生命周期为Pausing,中间状态,正在进行pause动作
        prev.setState(PAUSING, "startPausingLocked");
        ...

        // 当前resumed的Activity进程线程都存在,命中if
        // 构建PauseActivityItem对象,去执行pause对应的Activity
        //需要特别声明,在这里最后就会调用到对应 Activity 进程中,执行 onPause() 方法
        if (prev.app != null && prev.app.thread != null) {
            try {
                ...

                //prev就是当前stack中的 mResumedActivity,也就是正处于resumed状态的Activity
                //最后是放到 prev.app.thread 去执行的
                mService.getLifecycleManager().scheduleTransaction(prev.app.thread, prev.appToken,
                        PauseActivityItem.obtain(prev.finishing, userLeaving,
                                prev.configChangeFlags, pauseImmediately));
            } catch (Exception e) {
                //捕获到异常时,将相关标识都清空
                mPausingActivity = null;
                mLastPausedActivity = null;
                mLastNoHistoryActivity = null;
            }
        //如果进程或者线程不存在,直接将mPausingActivity、mLastPausedActivity、mLastNoHistoryActivity置空
        } else {
            mPausingActivity = null;
            mLastPausedActivity = null;
            mLastNoHistoryActivity = null;
        }

        //当前不是sleep状态,去获取 wakeLock,确保不会进入sleep状态
        if (!uiSleeping && !mService.isSleepingOrShuttingDownLocked()) {
            mStackSupervisor.acquireLaunchWakelock();
        }

        // 如果此时mPausingActivity不为空,命中if
        // 根据传入的pauseImmediately决定是否要同步finish Activity
        if (mPausingActivity != null) {
            //当前流程下传入的uiSleeping是false,命中if
            //暂停mPausingActivity按键的分发
            if (!uiSleeping) {
                prev.pauseKeyDispatchingLocked();
            } else if (DEBUG_PAUSE) {
                Slog.v(TAG_PAUSE, "Key dispatch not paused for screen off");
            }

            // 是否需要立即pause,如果需要命中if
            // 将当前Stack中的mPausingActivity设置生命周期为Paused,并且将
            //mPausingActivity置空,返回false
            if (pauseImmediately) {
                completePauseLocked(false, resuming);
                return false;

            // 如果不需要立即pause,那么500ms后再去completePauseLock,这里返回 true
            //构建出的消息最后也会调用到 completePauseLock() 函数,区别在于在此处最后还会尝试去
            //resume mFocusedStack 最顶层的Activity
            } else {
                schedulePauseTimeout(prev);
                return true;
            }

        // 如果mPausingActivity为空,命中else
        // mPausingActivity为null只有两种情况:
        // 1. prev进程线程存在的情况下,scheduleTransaction()抛出异常,从而设置了scheduleTransaction为null
        // 2. prev进程线程不存在,设置mPausingActivity为null,此种情况下即已经完成了prev的pause
        } else {
            ...
        }
    }
  • 解析该函数,除去执行条件判断,主要完成了如下的动作:
    1. mPausingActivitymLastPausedActivity 保存下待Pause的Activity,也就是 mResumedActivity ;根据 mResumedActivity 中相关标志位(FLAG_ACTIVITY_NO_HISTORY\FLAG_NO_HISTORY)判断是否需要将其保存到 mLastNoHistoryActivity 中代表不需要将该Activity保存到历史堆栈中
    2. mResumedActivity 的生命周期设置为 PAUSING 状态
    3. 构建 PauseActivityItem 对象去执行 Pause 流程
    4. 根据传入的 pauseImmediately 参数,决定是否立即执行 completePauseLocked() 函数,在当前流程中是会延迟去complete,也就是在当前流程中调用的是 schedulePauseTimeout() 函数
  • 在以上流程中,我们重点关注的是第三步和第四步,接下来就逐一分析

1.2.1 PauseActivityItem

  1. ClientLifecycleManager.scheduleTransaction()

    frameworks\base\services\core\java\com\android\server\am\ClientLifecycleManager.java

    //解析一下入参:
    //client : mResumedActivity对应的ActivityThread中的内部类 ApplicationThread
    //activityToken:mResumedActivity中的 appToken 成员变量
    //stateRequest:构造的PauseActivityItem对象
    void scheduleTransaction(@NonNull IApplicationThread client, @NonNull IBinder activityToken,
                             @NonNull ActivityLifecycleItem stateRequest) throws RemoteException {
        //先构造出 clientTransaction 对象
        final ClientTransaction clientTransaction = transactionWithState(client, activityToken,
                                                                         stateRequest);
        //调用重载函数
        scheduleTransaction(clientTransaction);
    }
    
    void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
        //获取到传入的clientTransaction对象中的mClient变量
        final IApplicationThread client = transaction.getClient();
        //调用传入的 transaction 的schedule()方法
        transaction.schedule();
        //如果获取到的client不是继承binder的,那么transaction需要回收
        if (!(client instanceof Binder)) {
            transaction.recycle();
        }
    }
    
    • 可以看到在 scheduleTransaction() 函数中,先根据入参构建出了 ClientTransaction 对象;然后调用重载函数,调用到 ClientTransaction.schedule() 函数
  2. ClientTransaction.schedule()

    frameworks\base\core\java\android\app\servertransaction\ClientTransaction.java

    public void schedule() throws RemoteException {
        //调用 IApplicationThread中的方法
        mClient.scheduleTransaction(this);
    }
    
    • mClient 就是mResumedActivity对应的ActivityThread中的内部类 ApplicationThread
  3. ActivityThread$ApplicationThread.scheduleTransaction()

    frameworks\base\core\java\android\app\ActivityThread.java

    @Override
    public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
        //又走到ActivityThread中的同名方法中,这里是调用到ActivityThread的父类中去
        ActivityThread.this.scheduleTransaction(transaction);
    }
    
    • 这里就是调用到外部类,也就是 ActivityThread.scheduleTransaction() 函数中,本质是调用到 ActivityThread 的父类 ClientTransactionHandler
  4. ClientTransactionHandler.scheduleTransaction()

    frameworks\base\core\java\android\app\ClientTransactionHandler.java

    void scheduleTransaction(ClientTransaction transaction) {
        //先执行 preExecute()
        transaction.preExecute(this);
        //再通过handle发送EXECUTE_TRANSACTION执行相应操作
        sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
    }
    
    • 可以看到先去执行了 ClientTransaction.preExecute() 函数,在当前流程中,preExecute() 没有执行任何动作,在此处先不做分析,在后续create\resume 流程中再去细说;再通过Handle,发送 EXECUTE_TRANSACTION进行下一步处理
  5. handleMessage()

    frameworks\base\core\java\android\app\ActivityThread.java

    public void handleMessage(Message msg) {
        ...
        switch (msg.what) {
            ...
    		case EXECUTE_TRANSACTION:
                //取出ClientTransaction对象
        		final ClientTransaction transaction = (ClientTransaction) msg.obj;
                //调用TransactionExecutor去触发执行ClientTransaction里面的流程
        		mTransactionExecutor.execute(transaction);
                //如果是系统ActivityThread,那么需要回收ClientTransaction对象
        		if (isSystem()) {
                	transaction.recycle();
            	}
        	break;
            ...
        }
        ...
    }
    
    • handle中又会借助 TransactionExecutor 对象去触发执行 ClientTransaction
  6. TransactionExecutor.execute()

    frameworks\base\core\java\android\app\servertransaction\TransactionExecutor.java

    public void execute(ClientTransaction transaction) {
    
        //先执行 callback 中的execute
        executeCallbacks(transaction);
    
        //再执行 lifecycleItem的execute
        executeLifecycleState(transaction);
        //清空 pendingActions 列表
        mPendingActions.clear();
    }
    
    • 可以看到在 TransactionExecutor.execute() 中,会先去触发执行 callback 中的流程,而因为当前流程下,没有callback对象,所以跳过callback步骤,直接看 executeLifecycleState() 函数
  7. TransactionExecutor.executeLifecycleState()

    frameworks\base\core\java\android\app\servertransaction\TransactionExecutor.java

    • 在这之前先说明一下 ClientTransaction 中保存的相关成员变量,具体的流程可以自行分析 ClientTransaction 的构建
      • mClientmResumedActivity对应的ActivityThread中的内部类 ApplicationThread
      • mActivityTokenmResumedActivity中的 appToken 成员变量
      • mLifecycleStateRequest:构建的 PauseActivityItem 对象
    private void executeLifecycleState(ClientTransaction transaction) {
        //拿到ClientTransaction中的ActivityLifecycleItem对象,确保不为空
        //当前lifecycleItem就是PauseActivityItem对象
        final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
        ...
    
        //拿到ClientTransaction中的token,也就是 mResumedActivity
        //中的 appToken 成员变量
        final IBinder token = transaction.getActivityToken();
        //通过appToken拿到ActivityClientRecord对象,在mResumedActivity 的
        //ActivityThread中获取到
        final ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
    
        ...
    
        //调用cycleToPath(),去补齐需要执行的生命周期,此时 r 的生命周期为 ON_RESUME,
        //PauseActivityItem的目标生命周期为ON_PAUSE,这之间没有中间状态
        cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */);
    
        //开始执行,当前流程下,就是执行 PauseActivityItem.execute()
        lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
        lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
    }
    
    • 抛开对应变量的获取,在该函数中就是在去执行 PauseActivityItem.execute()PauseActivityItem.postExecute();其中的 cycleToPath() 函数因为当前流程中并没有涉及,我们放到后面 ON_START 流程中进行解析
  8. PauseActivityItem.execute()

    frameworks\base\core\java\android\app\servertransaction\PauseActivityItem.java

    public void execute(ClientTransactionHandler client, IBinder token,
                        PendingTransactionActions pendingActions) {
        Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
        //调用到ActivityThread中的handlePauseActivity() 函数
        client.handlePauseActivity(token, mFinished, mUserLeaving, mConfigChanges, pendingActions,
                                   "PAUSE_ACTIVITY_ITEM");
        Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
    }
    
    • 这里也就又走到了 mResumedActivityActivityThread 中了
  9. ActivityThread.handlePauseActivity()

    frameworks\base\core\java\android\app\ActivityThread.java

    @Override
    public void handlePauseActivity(IBinder token, boolean finished, boolean userLeaving,
                                    int configChanges, PendingTransactionActions pendingActions, String reason) {
        //根据token(也就是ActivityRecord中的appToken对象)拿到对应的 ActivityClientRecord 对象
        ActivityClientRecord r = mActivities.get(token);
        //首先保证能够拿到对应的 ActivityClientRecord 对象
        if (r != null) {
            //如果userLeaving为true,那么最后就会去调用到Activity中的 onUserInteraction()和
            //onUserLeaveHint() 函数
            if (userLeaving) {
                performUserLeavingActivity(r);
            }
    
            //保存下configChanges的值
            r.activity.mConfigChangeFlags |= configChanges;
            //进行paused
            performPauseActivity(r, finished, reason, pendingActions);
    
            //如果当前是 Android 3.0 或者之前的版本,命中if
            if (r.isPreHoneycomb()) {
                QueuedWork.waitToFinish();
            }
            //mSomeActivitiesChanged置true,代表当前有Activity状态变化
            mSomeActivitiesChanged = true;
        }
    }
    
    • 该函数中完成的操作也比较一目了然,顺着流程,调用到 performPauseActivity()
  10. ActivityThread.performPauseActivity()

    frameworks\base\core\java\android\app\ActivityThread.java

    private Bundle performPauseActivity(ActivityClientRecord r, boolean finished, String reason,
                                        PendingTransactionActions pendingActions) {
        //如果传入的 ActivityClientRecord 状态已经是 paused,那么就不需要
        //再进行pause
        if (r.paused) {
            ...
        }
        //如果传入的Activity是finish状态的,那么设置activity.mFinished为true
        if (finished) {
            r.activity.mFinished = true;
        }
    
        ...
    
        //继续调用去pause
        performPauseActivityIfNeeded(r, reason);
    
        //拿到该Activity的所有 onPause 监听
        ArrayList<OnActivityPausedListener> listeners;
        synchronized (mOnPauseListeners) {
            listeners = mOnPauseListeners.remove(r.activity);
        }
        //调用所有监听的 onPaused() 方法
        int size = (listeners != null ? listeners.size() : 0);
        for (int i = 0; i < size; i++) {
            listeners.get(i).onPaused(r.activity);
        }
        ...
    
        return shouldSaveState ? r.state : null;
    }
    
    • 同样继续调用 performPauseActivityIfNeeded() 完成Pause操作
  11. ActivityThread.performPauseActivityIfNeeded()

    frameworks\base\core\java\android\app\ActivityThread.java

    private void performPauseActivityIfNeeded(ActivityClientRecord r, String reason) {
        //如果已经是 paused 状态,那么直接返回
        if (r.paused) {
            return;
        }
    
        try {
            //设置mCalled初始值为false
            r.activity.mCalled = false;
            //借助Instrumentation去调用onPause
            mInstrumentation.callActivityOnPause(r.activity);
            //mCalled为false是会命中if,代表没有调用基类 Activity 中的 onPause() 方法,
            //当 mCalled 为false时,会抛出异常,也就是说必须调用基类Activity的onPause()
            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) {
            ...
        }
        //将该Activity设置状态为 pause
        r.setState(ON_PAUSE);
    }
    
    • 接下来就是借助 Instrumentation 再调用到 Activity 中的 onPause() 方法中,后续流程比较简单,就不做展开分析
  12. ActivityStack.activityPausedLocked()

    frameworks\base\services\core\java\com\android\server\am\ActivityStack.java

    • 在前面我们还留了个小尾巴,就是 PauseActivityItem.postExecute() 方法,在该方法中最后会调用到 AMS.activityPaused() 中,然后又会调用到 mResumedActivity 所属的Stack中的 activityPausedLocked()方法中,接下来再看一下该函数
    final void activityPausedLocked(IBinder token, boolean timeout) {
    
        //如果对应stack和task中存在token所对应的Activity,那么此时r就不为空
        final ActivityRecord r = isInStackLocked(token);
        //能够正确获取到r时,命中if
        if (r != null) {
            //移除 PAUSE_TIMEOUT_MSG 消息
            mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
            //如果此时mPausingActivity就是传入的Activity,那么直接去complete pause mPausingActivity
            if (mPausingActivity == r) {
                mService.mWindowManager.deferSurfaceLayout();
                try {
                    //进行complete Pause,此处传入的resumeNext为true,代表需要进行resume Activity动作
                    completePauseLocked(true /* resumeNext */, null /* resumingActivity */);
                } finally {
                    mService.mWindowManager.continueSurfaceLayout();
                }
                return;
            //如果mPausingActivity不是传入的Activity,命中else
            } else {
                //如果当前传入的Activity生命周期是PAUSING,那么需要设置其生命周期为PAUSED
                if (r.isState(PAUSING)) {
                    r.setState(PAUSED, "activityPausedLocked");
                    if (r.finishing) {
                        finishCurrentActivityLocked(r, FINISH_AFTER_VISIBLE, false,
                                                    "activityPausedLocked");
                    }
                }
            }
        }
        //校正系统中所有Activity的可见性
        mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
    }
    
    • 在该函数中,首先会判断能够根据传入的 ActivityRecord.appToken 在对应的 stackTask 中获取到对应的 ActivityRecord 对象,在可以获取到并且系统中的 mPausingActivity 就是当前获取到的 ActivityRecord 时,会接着去调用 completePauseLocked() 去完成 Pause 操作,并且根据此处传参 resumeNext = true ,还会去 Resume 对应 stack 最顶部的Activity
  13. ActivityStack.completePauseLocked()

    frameworks\base\services\core\java\com\android\server\am\ActivityStack.java

    // 将当前Stack中的mPausingActivity给设置生命周期为Paused,并且将mPausingActivity置空,并且由
    //resumeNext 参数决定,是否需要去 resume Activity
    private void completePauseLocked(boolean resumeNext, ActivityRecord resuming) {
        // 拿到当前Stack中的mPausingActivity
        ActivityRecord prev = mPausingActivity;
        if (DEBUG_PAUSE)
            Slog.v(TAG_PAUSE, "Complete pause: " + prev);
    
        // 如果该Stack中的mPausingActivity不为空,命中if
        // 结束该mPausingActivity,并将mPausingActivity置为空
        if (prev != null) {
            // 设置mPausingActivity
            prev.setWillCloseOrEnterPip(false);
            // 判断mPausingActivity生命周期是否是STOPPING
            final boolean wasStopping = prev.isState(STOPPING);
            // 设置mPausingActivity的生命周期为PAUSED
            prev.setState(PAUSED, "completePausedLocked");
            // 如果mPausingActivity是finishing状态,那么就去finish他
            if (prev.finishing) {
                if (DEBUG_PAUSE)
                    Slog.v(TAG_PAUSE, "Executing finish of activity: " + prev);
                // 结束 mPausingActivity,如果该mPausingActivity已从history中移除,那么此时拿到的返回值prev为空
                // 否则还为mPausingActivity
                prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE, false,
                                                   "completedPausedLocked");
            //如果mPausingActivity所属的app还在,命中else if
            //根据相关标志执行对应动作
            } else if (prev.app != null) {
                if (DEBUG_PAUSE)
                    Slog.v(TAG_PAUSE, "Enqueue pending stop if needed: " + prev
                           + " wasStopping=" + wasStopping + " visible=" + prev.visible);
                //将 mPausingActivity 从 mActivitiesWaitingForVisibleActivity列表中移除
                if (mStackSupervisor.mActivitiesWaitingForVisibleActivity.remove(prev)) {
                    if (DEBUG_SWITCH || DEBUG_PAUSE)
                        Slog.v(TAG_PAUSE,
                               "Complete pause, no longer waiting: " + prev);
                }
                //判断是否在paused完成后,进行relaunch操作
                if (prev.deferRelaunchUntilPaused) {
                    prev.relaunchActivityLocked(false /* andResume */,
                                                prev.preserveWindowOnDeferredRelaunch);
                    //判断 mPausingActivity 是否是处在 Stopping 状态,如果是,则重新将生命周期设置为 Stopping
                } else if (wasStopping) {
                    prev.setState(STOPPING, "completePausedLocked");
                    //如果 mPausingActivity 不可见或者 需要进入sleep/shut down,命中else if
                    //将 mPausingActivity 添加到 mStoppingActivities 列表中,并且直接触发该Activity的stop操作
                } else if (!prev.visible || shouldSleepOrShutDownActivities()) {
                    prev.setDeferHidingClient(false);
    
                    addToStopping(prev, true /* scheduleIdle */, false /* idleDelayed */);
                }
                //除上面的情况下,都直接将prev置空
            } else {
               
                prev = null;
            }
    		...
            //将 mPausingActivity 置空
            mPausingActivity = null;
        }
    
        // 如果传入的resumeNext为true,命中if,会去resume当前mFocusedStack上最顶层的Activity
        if (resumeNext) {
            // 拿到 mFocusedStack
            final ActivityStack topStack = mStackSupervisor.getFocusedStack();
            //不是sleep的,去resume mFocusedStack最顶层的Activity
            if (!topStack.shouldSleepOrShutDownActivities()) {
                mStackSupervisor.resumeFocusedStackTopActivityLocked(topStack, prev, null);
            } else {
                checkReadyForSleep();
                ActivityRecord top = topStack.topRunningActivityLocked();
                if (top == null || (prev != null && top != prev)) {
                    mStackSupervisor.resumeFocusedStackTopActivityLocked();
                }
            }
        }
    
        // 如果mPausingActivity不为空,命中if
        // 检测mPausingActivity所在Process的情况
        if (prev != null) {
            ...
        }
        
        //如果 存在自由窗口Stack 或者 可见性发生变化时,命中if
        //需要通知相关的Task Stack改变,并将 mAppVisibilitiesChangedSinceLastPause 置回false
        if (mStackSupervisor.mAppVisibilitiesChangedSinceLastPause
            || getDisplay().hasPinnedStack()) {
            mService.mTaskChangeNotificationController.notifyTaskStackChanged();
            mStackSupervisor.mAppVisibilitiesChangedSinceLastPause = false;
        }
    
        // 确保传入的resuming Activity可见
        mStackSupervisor.ensureActivitiesVisibleLocked(resuming, 0, !PRESERVE_WINDOWS);
    }
    
    • 在该函数中,就会去将 mPausingActivity 的生命周期设置为 PAUSED,并且将 mPausingActivity 置空,代表 Pause 完成,然后根据传入的 resumeNext 参数决定是否需要在此处触发 resume Activity 的动作,最后会去校正 系统中Activity的可见性
  • 至此 PauseActivityItem 对象下的 Pause 流程就全部梳理完毕了

1.2.2 schedulePauseTimeout()

  • schedulePauseTimeout() 流程较为简单,其实就是通过 Handle 延迟500ms后再去调用 activityPausedLocked(),之后和上面的流程基本相同,此处就不展开分析了

  • 从目前来看,此时的 mPausingActivity.visible 还是等于 true 的

  • ActivityStack.resumeTopActivityInnerLocked() 中的 startPausingLocked() 中调用 onPaused()

    • mService.getLifecycleManager().scheduleTransaction(prev.app.thread, prev.appToken, PauseActivityItem.obtain(prev.finishing, userLeaving, prev.configChangeFlags, pauseImmediately));

    • PauseActivityItem.execute()

      • client.handlePauseActivity(token, mFinished, mUserLeaving, mConfigChanges, pendingActions, "PAUSE_ACTIVITY_ITEM");
      1. 这个client就是 scheduleTransaction(prev.app.thread…)中的 prev.app.thread 也就是prev的线程中去调用的

      2. token 就是 prev.appToken

      3. mFinished 就是 prev.finishing

      4. mUserLeaving 就是 userLeaving

      5. mConfigChanges 就是 prev.configChangeFlags

        • performPauseActivity()
          • performPauseActivityIfNeeded()
            • mInstrumentation.callActivityOnPause()
              • activity.performPause()
                • onPause()

② oncreate

  • 根据上篇文章的分析,可以知道 onCreate() 流程的起点是在 realStartActivityLocked() 中进入的,我们就从该函数关键代码处开始解析

2.1 realStartActivityLocked()

frameworks\base\services\core\java\com\android\server\am\ActivityStackSupervisor.java

final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
                                      boolean andResume, boolean checkConfig) throws RemoteException {
    ...
    final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
                                                                         r.appToken);
    //构建出LaunchActivityItem作为callback添加到ClientTransaction对象中
    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));
	//设置Activity所需的最终状态
    final ActivityLifecycleItem lifecycleItem;
    //如果Activity最后是需要resume的,那么构建出ResumeActivityItem作为lifecycleItem
    if (andResume) {
        lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
    } else {
        lifecycleItem = PauseActivityItem.obtain();
    }
    //将lifecycleItem保存到clientTransaction中
    clientTransaction.setLifecycleStateRequest(lifecycleItem);

    //开始执行clientTransaction,这里最后就会调用TransactionExecutor.execute()方法
    //而在这个方法中,会先去执行callback,在此处即LaunchActivityItem.execute(),完成后
    //再去执行lifecycleItem.execute()
    mService.getLifecycleManager().scheduleTransaction(clientTransaction);
    ...
}
  • 排除掉与当前主题无关的代码,可以看到在该函数中,同样构建了 clientTransaction 对象 和 LaunchActivityItem 对象,不过和 [onPause](① onPause) 流程不同的是 在当前流程中,LaunchActivityItem 对象是作为 callback 被添加到 clientTransaction 对象中,最后同样调用 scheduleTransaction() 触发,这部分流程和上面并无差异,也不再详细解析,直接看最后的执行流程

2.2 TransactionExecutor.executeCallbacks()

frameworks\base\core\java\android\app\servertransaction\TransactionExecutor.java

@VisibleForTesting
public void executeCallbacks(ClientTransaction transaction) {
    //拿到ClientTransaction中的callback对象
    final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
    //如果没有callback,直接返回
    if (callbacks == null) {
        return;
    }
    log("Resolving callbacks");

    //通过 ActivityRecord.appToken变量拿到对应的 ActivityClientRecord 对象
    final IBinder token = transaction.getActivityToken();
    ActivityClientRecord r = mTransactionHandler.getActivityClient(token);

    ...

    //取出每个callback去触发
    final int size = callbacks.size();
    for (int i = 0; i < size; ++i) {
        ...
        //执行execute()和postExecute()
        item.execute(mTransactionHandler, token, mPendingActions);
        item.postExecute(mTransactionHandler, token, mPendingActions);
        ...
    }
}
  • 其实和上面的流程很类似,同样是调用到callback.execute()callback.postExecute(),而当前流程下就是调用 LaunchActivityItem.execute()LaunchActivityItem.postExecute(),而针对 LaunchActivityItem 对象来说, postExecute() 函数是未实现的,所以无需关心,只关注 execute() 函数即可

2.3 LaunchActivityItem.execute()

frameworks\base\core\java\android\app\servertransaction\LaunchActivityItem.java

@Override
public void execute(ClientTransactionHandler client, IBinder token,
                    PendingTransactionActions pendingActions) {
    Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
    //根据传入的数据构建出 ActivityClientRecord 对象
    ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
                                                      mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
                                                      mPendingResults, mPendingNewIntents, mIsForward,
                                                      mProfilerInfo, client);
    //调用到待启动的Activity的 ActivityThread.handleLaunchActivity() 函数
    client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
    Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
  • 可以看到,针对经历完整生命周期启动的Activity,其对应的 ActivityClientRecord 对象是在 LaunchActivityItem 对象中进行创建的,后续继续调用其 ActivityThread.handleLaunchActivity() 函数去继续启动

2.4 ActivityThread.handleLaunchActivity()

frameworks\base\core\java\android\app\ActivityThread.java

@Override
public Activity handleLaunchActivity(ActivityClientRecord r,
                                     PendingTransactionActions pendingActions, Intent customIntent) {
    //移除GC_WHEN_IDLE消息,存在GC任务的前提下,移除mGcIdler
    unscheduleGcIdler();
    //标识activity状态变化,这个只有在初始化之前和GC之后才会为false
    mSomeActivitiesChanged = true;

    //如果存在profilerInfo,那么设置profilerInfo
    if (r.profilerInfo != null) {
        mProfiler.setProfiler(r.profilerInfo);
        mProfiler.startProfiling();
    }

    //处理 config 的变化
    handleConfigurationChanged(null, null);

    //如果没有禁用 Render,那么调用earlyInitEGL()
    if (!ThreadedRenderer.sRendererDisabled) {
        GraphicsEnvironment.earlyInitEGL();
    }
    //在WindowManagerGlobal中获取到 WMS 的IBinder,用于和WMS进行通讯
    WindowManagerGlobal.initialize();

    //开始启动 Activity,启动成功,则返回对应的Activity
    final Activity a = performLaunchActivity(r, customIntent);

    //如果启动成功,则会命中if
    if (a != null) {
        r.createdConfig = new Configuration(mConfiguration);
        reportSizeConfigurations(r);
        //如果当前的Activity不是finish状态,且pendingActions不为空,
        //那么需要将当前Activity的状态存到 pendingActions 中,代表后续可以进行恢复
        if (!r.activity.mFinished && pendingActions != null) {
            pendingActions.setOldState(r.state);
            pendingActions.setRestoreInstanceState(true);
            pendingActions.setCallOnPostCreate(true);
        }
    //如果启动不成功,命中else,结束该Activity
    } else {
        try {
            ActivityManager.getService()
                .finishActivity(r.token, Activity.RESULT_CANCELED, null,
                                Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
    }

    //返回activity对象
    return a;
}
  • 在该函数中,会进行新启动Activity的一些初始环境准备,然后就会调用 performLaunchActivity() 函数根据传入的 ActivityClientRecord 对象去构建出 Activity 对象

2.5 ActivityThread.performLaunchActivity()

frameworks\base\core\java\android\app\ActivityThread.java

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    //根据传入的ActivityClientRecord获取到activityInfo
    ActivityInfo aInfo = r.activityInfo;
    //如果传入的clientRecord没有packageInfo,那么尝试获取到对应的packageInfo
    if (r.packageInfo == null) {
        r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
                                       Context.CONTEXT_INCLUDE_CODE);
    }

    //拿到 component
    ComponentName component = r.intent.getComponent();
    if (component == null) {
        component = r.intent.resolveActivity(
            mInitialApplication.getPackageManager());
        r.intent.setComponent(component);
    }

    if (r.activityInfo.targetActivity != null) {
        component = new ComponentName(r.activityInfo.packageName,
                                      r.activityInfo.targetActivity);
    }

    //创建出 ContextImpl 对象
    ContextImpl appContext = createBaseContextForActivity(r);
    Activity activity = null;
    try {
        //通过 ContextImpl 获取到 classLoader
        java.lang.ClassLoader cl = appContext.getClassLoader();
        //在Instrumentation中借助ClassLoader反射创建出 Activity 对象
        activity = mInstrumentation.newActivity(
            cl, component.getClassName(), r.intent);
        //严格模式下,需要对activity进行计数
        StrictMode.incrementExpectedActivityCount(activity.getClass());
        r.intent.setExtrasClassLoader(cl);
        r.intent.prepareToEnterProcess();
        if (r.state != null) {
            r.state.setClassLoader(cl);
        }
    } catch (Exception e) {
        ...
    }

    try {
        Application app = r.packageInfo.makeApplication(false, mInstrumentation);
        
        //如果activity创建成功,命中if
        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对象,如果当前的 Activity 需要保留窗口,且待删除的窗口不为空
            //那么就将待删除的窗口赋值给window,然后将待删除窗口置空
            Window window = null;
            if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
                window = r.mPendingRemoveWindow;
                r.mPendingRemoveWindow = null;
                r.mPendingRemoveWindowManager = null;
            }
            appContext.setOuterContext(activity);
            //activity启动前 window 相关的变量构建,构建了 PhoneWindow 和 WindowManagerImpl
            //其中 r.token 是个 IBinder,对应的就是 AMS 中的ActivityRecord,此处存在待删除窗口时
            //传入的window才不为空
            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
            activity.mStartedActivity = false;
            //如果有theme资源,那么设置theme到该activity中
            int theme = r.activityInfo.getThemeResource();
            if (theme != 0) {
                activity.setTheme(theme);
            }

            //同样设置activity的mCalled初始值为false
            activity.mCalled = false;
            //调用 onCreate() 方法
            if (r.isPersistable()) {
                mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
            } else {
                mInstrumentation.callActivityOnCreate(activity, r.state);
            }
            //同pause一样,如果没有调用基类Activity的onCreate()方法,mCalled为false,命中if
            //抛出异常,所以必须调用基类Activity的onCreate()方法
            if (!activity.mCalled) {
                throw new SuperNotCalledException(
                    "Activity " + r.intent.getComponent().toShortString() +
                    " did not call through to super.onCreate()");
            }
            //将创建出来的Activity对象同样记录到ActivtyClientRecord中
            r.activity = activity;
        }
        //设置状态为 ON_CREATE
        r.setState(ON_CREATE);

        //将当前的 ActivityClientRecord 以 token(其实就是ActivityRecord中的appToken对象)
        //为key存到ActivityThread 的 mActivities 中
        mActivities.put(r.token, r);

    } catch (SuperNotCalledException e) {
        throw e;

    } catch (Exception e) {
        ...
    }

    return activity;
}
  • 在该函数中,可以看到,借助 Instrumentation 对象创建出了 Activity 对象,最后同样是借助 Instrumentation.callActivityOnCreate() 调用到 Activity.onCreate() 方法;

  • 那么至此,onCreate()流程也解析完毕

③ onstart

  • onStart流程作为一个中间过渡状态,并不如 上面几个流程一样,有对应的 ActivityLifecycleItem 对象进行触发,他是在执行完 onCreate() 之后,嵌入在 TransactionExecutor.execute() 函数中的,接下来让我们继续解析

3.1 TransactionExecutor.execute()

frameworks\base\core\java\android\app\servertransaction\TransactionExecutor.java

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

    //先执行 callback 中的execute
    executeCallbacks(transaction);

    //再执行 lifecycleItem的execute
    executeLifecycleState(transaction);
    mPendingActions.clear();
    log("End resolving transaction");
}
  • 通过上面的分析,我们知道在 executeCallbacks() 函数中完成了 onCreate() 流程,接下来就是 executeLifecycleState() 函数

3.2 TransactionExecutor.executeLifecycleState()

frameworks\base\core\java\android\app\servertransaction\TransactionExecutor.java

private void executeLifecycleState(ClientTransaction transaction) {
    //拿到ClientTransaction中的ActivityLifecycleItem对象,确保不为空
    //当前lifecycleItem就是ResumeActivityItem对象
    final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
    if (lifecycleItem == null) {
        // No lifecycle request, return early.
        return;
    }

    //拿到ClientTransaction中的token和ActivityClientRecord
    final IBinder token = transaction.getActivityToken();
    final ActivityClientRecord r = mTransactionHandler.getActivityClient(token);

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

    //调用cycleToPath(),当前lifecycleItem.getTargetState()拿的就是ON_RESUME
    cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */);

    //开始执行,当前流程下,就是执行 ResumeActivityItem.execute()
    lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
    lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
}
  • 在该函数中,会先去获取 ClientTransaction 对象中的 ActivityLifecycleItem对象,而该对象,根据 onCreate 流程中的分析,我们可以知道就是 ResumeActivityItem 对象,那么接下去就是去执行 cycleToPath() 函数

3.3 TransactionExecutor.cycleToPath()

frameworks\base\core\java\android\app\servertransaction\TransactionExecutor.java

private void cycleToPath(ActivityClientRecord r, int finish,
                         boolean excludeLastState) {
    //拿到ActivityClientRecord当前的状态,当前流程下是ON_CREATE
    final int start = r.getLifecycleState();
    log("Cycle from: " + start + " to: " + finish + " excludeLastState:" + excludeLastState);
    //调用getLifecyclePath(),此时start=ON_CREATE,finish=ON_RESUME,excludeLastState=true
    //这个就是去拿中间状态,当前流程下拿到的是 ON_START
    final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
    //处理中间状态
    performLifecycleSequence(r, path);
}
  • 该函数中会去拿当前还需要执行的中间状态,该函数也比较简单

frameworks\base\core\java\android\app\servertransaction\TransactionExecutorHelper.java

@VisibleForTesting
public IntArray getLifecyclePath(int start, int finish, boolean excludeLastState) {
    //首先要确保 start 和 finish 都是合法符合要求的
    if (start == UNDEFINED || finish == UNDEFINED) {
        throw new IllegalArgumentException("Can't resolve lifecycle path for undefined state");
    }
    if (start == ON_RESTART || finish == ON_RESTART) {
        throw new IllegalArgumentException(
            "Can't start or finish in intermittent RESTART state");
    }
    if (finish == PRE_ON_CREATE && start != finish) {
        throw new IllegalArgumentException("Can only start in pre-onCreate state");
    }

    //做一次mLifecycleSequence清空
    mLifecycleSequence.clear();
    //如果finish是大于等于start,那么就将中间状态都加到mLifecycleSequence中
    //当前的流程中,就会加上 ON_START
    if (finish >= start) {
        // just go there
        for (int i = start + 1; i <= finish; i++) {
            mLifecycleSequence.add(i);
        }
    //而如果finish小于start,则根据情况添加
    } else { // finish < start, can't just cycle down
        if (start == ON_PAUSE && finish == ON_RESUME) {
            // Special case when we can just directly go to resumed state.
            mLifecycleSequence.add(ON_RESUME);
        } else if (start <= ON_STOP && finish >= ON_START) {
            // Restart and go to required state.

            // Go to stopped state first.
            for (int i = start + 1; i <= ON_STOP; i++) {
                mLifecycleSequence.add(i);
            }
            // Restart
            mLifecycleSequence.add(ON_RESTART);
            // Go to required state
            for (int i = ON_START; i <= finish; i++) {
                mLifecycleSequence.add(i);
            }
        } else {
            // Relaunch and go to required state

            // Go to destroyed state first.
            for (int i = start + 1; i <= ON_DESTROY; i++) {
                mLifecycleSequence.add(i);
            }
            // Go to required state
            for (int i = ON_CREATE; i <= finish; i++) {
                mLifecycleSequence.add(i);
            }
        }
    }
    //如果传入的excludeLastState为true,且mLifecycleSequence不为空
    //那么删除mLifecycleSequence中最后一个状态数据
    if (excludeLastState && mLifecycleSequence.size() != 0) {
        mLifecycleSequence.remove(mLifecycleSequence.size() - 1);
    }

    //返回mLifecycleSequence
    return mLifecycleSequence;
}

? 其实就是根据Activity当前的状态和最终的状态进行判断,取出两者之间的中间状态,记录到 mLifecycleSequence 返回

3.4 TransactionExecutor.performLifecycleSequence()

frameworks\base\core\java\android\app\servertransaction\TransactionExecutorHelper.java

private void performLifecycleSequence(ActivityClientRecord r, IntArray path) {
    final int size = path.size();
    //处理path中所有的中间状态
    for (int i = 0, state; i < size; i++) {
        state = path.get(i);
        log("Transitioning to state: " + state);
        switch (state) {
            ...
            //当前流程只有一个ON_START,命中case,调用handleStartActivity()
            case ON_START:
                mTransactionHandler.handleStartActivity(r, mPendingActions);
                break;
            ...
        }
    }
}
  • 根据上一步拿到的中间状态,匹配对应的流程,当前流程下只有一个 ON_START 状态,所以最后就是去执行正启动Activity的 ActivityThread.handleStartActivity() 函数

3.5 ActivityThread.handleStartActivity()

frameworks\base\core\java\android\app\ActivityThread.java

@Override
public void handleStartActivity(ActivityClientRecord r,
                                PendingTransactionActions pendingActions) {
    //拿到ActivityClientRecord对应的Activity对象,不能为空,该对像在onCreate流程中已完成创建
    final Activity activity = r.activity;
    if (r.activity == null) {
        return;
    }
    //如果传入的Activity,已经start过了,那么就直接抛出异常返回
    if (!r.stopped) {
        throw new IllegalStateException("Can't start activity that is not stopped.");
    }
    //如果对应的Activity是finish状态的,也直接返回,不进行start
    if (r.activity.mFinished) {
        // TODO(lifecycler): How can this happen?
        return;
    }

    // Start
    //调用performStart()
    activity.performStart("handleStartActivity");
    //设置状态为 ON_START
    r.setState(ON_START);

    ...
}
  • 后面的流程就相对比较简单,调用链就是: Activity.performStart() --> mInstrumentation.callActivityOnStart() --> activity.onStart() ,这些流程也不再赘述了

④ onresume

  • 继续顺着流程往下梳理,我们已经完成了中间状态 onStart() ,接下来就是该走到正在启动Activity的最终状态,也就是 TransactionExecutor.executeLifecycleState() 中的 lifecycleItem.execute()lifecycleItem.postExecute(),在当前流程下,就是 ResumeActivityItem.execute()ResumeActivityItem.postExecute(),该段代码可见 [onstart](3.2 TransactionExecutor.executeLifecycleState()) 中的解析

4.1.1 ResumeActivityItem.execute()

frameworks\base\core\java\android\app\servertransaction\ResumeActivityItem.java

@Override
public void execute(ClientTransactionHandler client, IBinder token,
                    PendingTransactionActions pendingActions) {
    Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityResume");
    //处理resume相关事宜
    client.handleResumeActivity(token, true /* finalStateRequest */, mIsForward,
                                "RESUME_ACTIVITY");
    Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
  • 调用流程都类似,也是走到了正在启动的Activity的ActivityThread中去

4.1.2 ActivityThread.handleResumeActivity()

1

@Override
public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
                                 String reason) {
    //移除GC_WHEN_IDLE消息,如果有GC任务,移除 mGcIdler 任务
    unscheduleGcIdler();
    mSomeActivitiesChanged = true;
    
    //传入的token标识着对应的Activity,在这里执行 onResume()
    final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
    ...

}
  • 移除与当前流程无关的代码,我们可以看到其实很相似的,调用链是: ActivityThread.handleResumeActivity() --> ActivityThread.performResumeActivity() --> Activity.performResume() --> Instrumetation.callActivityOnResume() --> Activity.onResume() 后续流程也比较简单,就不做展开分析了

4.2.1 ResumeActivityItem.postExecute()

frameworks\base\core\java\android\app\servertransaction\ResumeActivityItem.java

@Override
public void postExecute(ClientTransactionHandler client, IBinder token,
                        PendingTransactionActions pendingActions) {
    try {
        //调用 AMS.activityResumed() 方法
        ActivityManager.getService().activityResumed(token);
    } catch (RemoteException ex) {
        throw ex.rethrowFromSystemServer();
    }
}

4.2.2 ActivityManagerService.activityResumed()

frameworks\base\services\core\java\com\android\server\am\ActivityManagerService.java

@Override
public final void activityResumed(IBinder token) {
    final long origId = Binder.clearCallingIdentity();
    synchronized(this) {
        //拿到token对应的ActivityRecord对象,复位其中的icicle和haveState
        ActivityRecord.activityResumedLocked(token);
        mWindowManager.notifyAppResumedFinished(token);
    }
    Binder.restoreCallingIdentity(origId);
}
  • 至此 onResume 的流程也分析完成。

⑤ onstop

  • 接下来让我们分析一下 onStop 流程,onStop 的流程入口是在 onResume 之后,具体是在 ActivityThread.handleResumeActivity() 函数中

5.1 ActivityThread.handleResumeActivity()

frameworks\base\core\java\android\app\ActivityThread.java

@Override
public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
                                 String reason) {
	...
    //赋值mNewActivities为当前Activity
    r.nextIdle = mNewActivities;
    mNewActivities = r;
    if (localLOGV) Slog.v(TAG, "Scheduling idle handler for " + r);
    //添加 Idler 任务,在该任务中就会进行 stop Activity
    Looper.myQueue().addIdleHandler(new Idler());
}
  • 不关注和当前 stop 流程无关的代码,我们可以看到在resume的最后,添加了一个 Idler 对象到 当前 thread 的MessageQueue

  • MessageQueue.addIdleHandler()

public void addIdleHandler(@NonNull IdleHandler handler) {
    if (handler == null) {
        throw new NullPointerException("Can't add a null IdleHandler");
    }
    synchronized (this) {
        mIdleHandlers.add(handler);
    }
}
  • 可以看到是将 Idler 对象添加到了 MessageQueue.mIdleHandlers 中,而在当前ActivityThread正式开始运行后,会在looper中进行message的处理

5.2 MessageQueue.next()

frameworks\base\core\java\android\os\MessageQueue.java

Message next() {
    ...
    for (;;) {
        if (nextPollTimeoutMillis != 0) {
            Binder.flushPendingCommands();
        }

        nativePollOnce(ptr, nextPollTimeoutMillis);

        ...
            //如果当前 idleHandler 的计数是小于0的,并且当前没有待处理的message或者还没到处理下一个message的时间
            //命中if,拿到 mIdleHandlers的大小,存在 pendingIdleHandlerCount 变量中
            if (pendingIdleHandlerCount < 0
                && (mMessages == null || now < mMessages.when)) {
                pendingIdleHandlerCount = mIdleHandlers.size();
            }
            //如果 mIdleHandlers 中没有数据,命中if
            //继续去等待message消息,继续阻塞
            if (pendingIdleHandlerCount <= 0) {
                // No idle handlers to run.  Loop and wait some more.
                mBlocked = true;
                continue;
            }

            //如果走到这里,说明 mIdleHandlers 中存在数据,那么这里就需要将其拿出来存到 mPendingIdleHandlers 中
            if (mPendingIdleHandlers == null) {
                mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
            }
            mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
        }

        //开始去处理从 mIdleHandlers 列表中拿出来的数据
        for (int i = 0; i < pendingIdleHandlerCount; i++) {
            final IdleHandler idler = mPendingIdleHandlers[i];
            mPendingIdleHandlers[i] = null; // release the reference to the handler

            boolean keep = false;
            try {
                //逐一调用 mIdleHandlers 中的 IdleHandler 元素的 queueIdle() 方法
                // queueIdle() 方法返回的就是 false
                keep = idler.queueIdle();
            } catch (Throwable t) {
                Log.wtf(TAG, "IdleHandler threw exception", t);
            }

            //肯定会命中该if,从 mIdleHandlers 中移除已经处理的 idler
            if (!keep) {
                synchronized (this) {
                    mIdleHandlers.remove(idler);
                }
            }
        }

        //处理完毕 IdleHandler,将数量重新置0
        pendingIdleHandlerCount = 0;
		...
    }
}
  • 可以看到,当 MessageQueue中没有待处理消息后,会去尝试获取mIdleHandlers中的对象,进行处理,而此时很显然 mIdleHandlers 中是存在数据的,即会调用到 idler.queueIdle() 函数

5.3 Idler.queueIdle()

frameworks\base\core\java\android\app\ActivityThread.java

public final boolean queueIdle() {
    //拿到当前需要处理的Activity
    ActivityClientRecord a = mNewActivities;
    boolean stopProfiling = false;
    //判断是否需要stop profile
    if (mBoundApplication != null && mProfiler.profileFd != null
        && mProfiler.autoStopProfiler) {
        stopProfiling = true;
    }
    //如果需要处理的Activity不为空,命中if
    if (a != null) {
        //将待处理的Activity置空,代表已进行处理
        mNewActivities = null;
        //这里就是拿到了AMS的Ibinder
        IActivityManager am = ActivityManager.getService();
        ActivityClientRecord prev;
        //处理所有的需要处理的Activity
        do {
            if (localLOGV) Slog.v(
                TAG, "Reporting idle of " + a +
                " finished=" +
                (a.activity != null && a.activity.mFinished));
            //如果拿到的Activity不为空且不为finish状态,那么就去stop该Activity
            if (a.activity != null && !a.activity.mFinished) {
                try {
                    //调用AMS中的activityIdle()方法
                    am.activityIdle(a.token, a.createdConfig, stopProfiling);
                    a.createdConfig = null;
                } catch (RemoteException ex) {
                    throw ex.rethrowFromSystemServer();
                }
            }
            prev = a;
            //拿到下一个需要处理的Activity
            a = a.nextIdle;
            prev.nextIdle = null;
        } while (a != null);
    }
    if (stopProfiling) {
        mProfiler.stopProfiling();
    }
    ensureJitEnabled();
    return false;
}
  • 在该函数中,就会去遍历取出存入的需要处理的Activity,借助 AMS进行处理

5.4 ActivityManagerService.activityIdle()

frameworks\base\services\core\java\com\android\server\am\ActivityManagerService.java

@Override
public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
    final long origId = Binder.clearCallingIdentity();
    synchronized (this) {
        //拿到传入的token(ActivityRecord中的appToken)所在的Stack
        ActivityStack stack = ActivityRecord.getStackLocked(token);
        //在stack不为空的情况下,处理对应的Activity
        if (stack != null) {
            ActivityRecord r =
                mStackSupervisor.activityIdleInternalLocked(token, false /* fromTimeout */,
                                                            false /* processPausingActivities */, config);
            if (stopProfiling) {
                if ((mProfileProc == r.app) && mProfilerInfo != null) {
                    clearProfilerLocked();
                }
            }
        }
    }
    Binder.restoreCallingIdentity(origId);
}
  • 继续调用 activityIdleInternalLocked() 进行处理

5.5 ActivityStackSupervisor.activityIdleInternalLocked()

frameworks\base\services\core\java\com\android\server\am\ActivityStackSupervisor.java

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

    //需要设置为finish状态的activity列表
    ArrayList<ActivityRecord> finishes = null;
    ArrayList<UserState> startingUsers = null;
    int NS = 0;
    int NF = 0;
    boolean booting = false;
    boolean activityRemoved = false;

    //拿到Ibinder对应的Activity对象
    ActivityRecord r = ActivityRecord.forTokenLocked(token);
    //在能正确获取到Activity的情况下,命中if
    if (r != null) {
        if (DEBUG_IDLE) Slog.d(TAG_IDLE, "activityIdleInternalLocked: Callers="
                               + Debug.getCallers(4));
        //移除IDLE_TIMEOUT_MSG消息
        mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
        //把对应Activity中的 launchTickTime 置为0,且移除LAUNCH_TICK_MSG消息
        r.finishLaunchTickingLocked();
        //如果是来自 IDLE_TIMEOUT_MSG 消息命中的调用,那么会命中if
        if (fromTimeout) {
            reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
        }

        //如果传入的config不为空,命中if
        if (config != null) {
            r.setLastReportedGlobalConfiguration(config);
        }

        //设置activityRecord.idle标志为true
        r.idle = true;

        //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
        //如果该Activity所处的Stack就是 mFocusedStack 或者函数的执行源自 IDLE_TIMEOUT_MSG消息,命中if
        //拿到系统是否正在启动
        if (isFocusedStack(r.getStack()) || fromTimeout) {
            booting = checkFinishBootingLocked();
        }
    }

    //如果 mFocuseStack.mResumedActivity.idle 为true,命中if
    //代表获取焦点的Activity正处在空闲状态
    if (allResumedActivitiesIdle()) {
        //如果待stop的Activity不为空,命中if
        //触发对应thread的GC操作
        if (r != null) {
            mService.scheduleAppGcsLocked();
        }

        //如果当前的wakelock是持有状态,命中if
        //移除LAUNCH_TIMEOUT_MSG消息,并且release wakelock
        if (mLaunchingActivity.isHeld()) {
            mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
            if (VALIDATE_WAKE_LOCK_CALLER &&
                Binder.getCallingUid() != Process.myUid()) {
                throw new IllegalStateException("Calling must be system uid");
            }
            mLaunchingActivity.release();
        }
        //设置activity的可见性等
        ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
    }

    //拿到所有需要操作stop的Activity
    final ArrayList<ActivityRecord> stops = processStoppingActivitiesLocked(r,
                                                                            true /* remove */, processPausingActivities);
    NS = stops != null ? stops.size() : 0;
    //如果mFinishingActivities不为空,将其设置到finishes中,然后清空
    if ((NF = mFinishingActivities.size()) > 0) {
        finishes = new ArrayList<>(mFinishingActivities);
        mFinishingActivities.clear();
    }

    if (mStartingUsers.size() > 0) {
        startingUsers = new ArrayList<>(mStartingUsers);
        mStartingUsers.clear();
    }

    //遍历stops,判断activity是否是finish状态,如果是则finish对应的Activity,否则stop
    for (int i = 0; i < NS; i++) {
        r = stops.get(i);
        final ActivityStack stack = r.getStack();
        if (stack != null) {
            if (r.finishing) {
                stack.finishCurrentActivityLocked(r, ActivityStack.FINISH_IMMEDIATELY, false,
                                                  "activityIdleInternalLocked");
            } else {
                //将相应Activity执行stop操作
                stack.stopActivityLocked(r);
            }
        }
    }

    //把本来就是finish状态的Activity,去destroy掉
    for (int i = 0; i < NF; i++) {
        r = finishes.get(i);
        final ActivityStack stack = r.getStack();
        if (stack != null) {
            activityRemoved |= stack.destroyActivityLocked(r, true, "finish-idle");
        }
    }

    if (!booting) {
        if (startingUsers != null) {
            for (int i = 0; i < startingUsers.size(); i++) {
                mService.mUserController.finishUserSwitch(startingUsers.get(i));
            }
        }
    }

    mService.trimApplications();
    //dump();
    //mWindowManager.dump();

    if (activityRemoved) {
        resumeFocusedStackTopActivityLocked();
    }

    return r;
}
  • 首先该函数的调用有两处来源

    1. 如当前流程通过 MessageQueue 进行触发
    2. 通过 handle 进行触发,而消息发送的调用就在 completeResumeLocked() 中的 mStackSupervisor.scheduleIdleTimeoutLocked(this);

    在调用到该函数后,会首先获取到需要进行stop操作的Activity,通过函数 processStoppingActivitiesLocked() 进行获取,获取到需要 stop 的Activity列表之后,在调用 stopActivityLocked() 去进行 stop 操作,逐一查阅

5.5.1 ActivityStackSupervisor.processStoppingActivitiesLocked()

frameworks\base\services\core\java\com\android\server\am\ActivityStackSupervisor.java

//返回需要进行stop的Activity列表
final ArrayList<ActivityRecord> processStoppingActivitiesLocked(ActivityRecord idleActivity,
                                                                boolean remove, boolean processPausingActivities) {
    ArrayList<ActivityRecord> stops = null;

    //如果当前系统中存在任一Stack中的mResumedActivity不可见,那么nowVisible就是false
    final boolean nowVisible = allResumedActivitiesVisible();
    //遍历mStoppingActivities列表
    for (int activityNdx = mStoppingActivities.size() - 1; activityNdx >= 0; --activityNdx) {
        ActivityRecord s = mStoppingActivities.get(activityNdx);
        //等待变可见列表中存在从 stopping列表中取出的Activity时,返回为true
        boolean waitingVisible = mActivitiesWaitingForVisibleActivity.contains(s);
        if (DEBUG_STATES) Slog.v(TAG, "Stopping " + s + ": nowVisible=" + nowVisible
                                 + " waitingVisible=" + waitingVisible + " finishing=" + s.finishing);
        //当前系统中每一个mResumedActivity都可见,且当前取出的Activity包含在mActivitiesWaitingForVisibleActivity列表中
        //命中if,将相应activity从mActivitiesWaitingForVisibleActivity移除
        if (waitingVisible && nowVisible) {
            //将该Activity从mActivitiesWaitingForVisibleActivity列表中移除
            mActivitiesWaitingForVisibleActivity.remove(s);
            //将waitingVisible复位为false
            waitingVisible = false;
            //如果取出的Activity是finish状态的,将其设置为不可见
            if (s.finishing) {
                if (DEBUG_STATES) Slog.v(TAG, "Before stopping, can hide: " + s);
                s.setVisibility(false);
            }
        }
        //如果传入的remove为true,命中if
        //整理mStoppingActivities列表,从中筛选出真正需要去stop的Activity,放到 stops 列表中返回
        if (remove) {
            //如果取出的Activity所在的Stack不为空,判断当前stack所处的display是否是sleep状态的
            final ActivityStack stack = s.getStack();
            final boolean shouldSleepOrShutDown = stack != null
                ? stack.shouldSleepOrShutDownActivities()
                : mService.isSleepingOrShuttingDownLocked();
            //如果waitingVisible为false或者对应display是sleep状态的,命中if
            if (!waitingVisible || shouldSleepOrShutDown) {
                //如果传入的processPausingActivities为false,并且当前判断的Activity是处于 Pausing状态
                //命中if,延迟10s后再处理stop,也就是先让他pause完,直接判断下一个activity
                if (!processPausingActivities && s.isState(PAUSING)) {
                    // Defer processing pausing activities in this iteration and reschedule
                    // a delayed idle to reprocess it again
                    //移除IDLE_TIMEOUT_MSG消息
                    removeTimeoutsForActivityLocked(idleActivity);
                    //延迟10s处理IDLE_TIMEOUT_MSG消息
                    scheduleIdleTimeoutLocked(idleActivity);
                    continue;
                }

                if (DEBUG_STATES) Slog.v(TAG, "Ready to stop: " + s);
                if (stops == null) {
                    stops = new ArrayList<>();
                }
                //如果满足了条件,将该Activity添加到stops列表中
                stops.add(s);

                // Make sure to remove it in all cases in case we entered this block with
                // shouldSleepOrShutDown
                //将该activity从 mActivitiesWaitingForVisibleActivity 和 mStoppingActivities 中移除
                mActivitiesWaitingForVisibleActivity.remove(s);
                mStoppingActivities.remove(activityNdx);
            }
        }
    }

    //返回stops列表
    return stops;
}
  • 可以看到,该函数中其中就是对 mStoppingActivities 列表中的Activity对象做了二次判断,符合要求的才会添加到返回列表中进行后续操作,那么 mStoppingActivities 列表又是在何处进行添加的呢?回头查阅 [Pause](① onPause) 流程可以看到在 completePauseLocked() 函数中,有这么一段:

    private void completePauseLocked(boolean resumeNext, ActivityRecord resuming) {
        // 拿到当前Stack中的mPausingActivity
        ActivityRecord prev = mPausingActivity;
        if (DEBUG_PAUSE)
            Slog.v(TAG_PAUSE, "Complete pause: " + prev);
    
        // 如果该Stack中的mPausingActivity不为空,命中if
        // 结束该mPausingActivity,并将mPausingActivity置为空
        if (prev != null) {
            ...
            if (prev.finishing) {
                ...
            } else if (prev.app != null) {
                ...
                if (prev.deferRelaunchUntilPaused) {
                    ...
                } else if (wasStopping) {
                 	...
                //如果 mPausingActivity 不可见或者 需要进入sleep/shut down,命中else if
                //将 mPausingActivity 添加到 mStoppingActivities 列表中,并且直接触发该Activity的stop操作
                } else if (!prev.visible || shouldSleepOrShutDownActivities()) {
                    // Clear out any deferred client hide we might currently have.
                    prev.setDeferHidingClient(false);
                    addToStopping(prev, true /* scheduleIdle */, false /* idleDelayed */);
                }
            }
            ...
        }
    	...
    }
    

    可以看到,当prev.visible 为 false的时候,即prev不可见的时候,会将其添加到 mStoppingActivities列表中

5.5.2 ActivityStack.stopActivityLocked()

frameworks\base\services\core\java\com\android\server\am\ActivityStack.java

final void stopActivityLocked(ActivityRecord r) {
    ...

    //当对应Activity进程线程都还存在,命中if
    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)");
            //设置当前的Activity为 STOPPING 状态
            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对象并触发执行
            mService.getLifecycleManager().scheduleTransaction(r.app.thread, r.appToken,
                                                               StopActivityItem.obtain(r.visible, r.configChangeFlags));
            if (shouldSleepOrShutDownActivities()) {
                r.setSleeping(true);
            }
            //延迟11s后发送STOP_TIMEOUT_MSG消息
            Message msg = mHandler.obtainMessage(STOP_TIMEOUT_MSG, r);
            mHandler.sendMessageDelayed(msg, STOP_TIMEOUT);
        } catch (Exception e) {
            ...
        }
    }
}
  • 在该函数中就会去构建出 StopActivityItem 对象,并触发执行,并且延迟 STOP_TIMEOUT 时间后发送 STOP_TIMEOUT_MSG 消息触发 ActivityRecordactivityStoppedLocked() 函数的执行
  • StopActivityItem 对象中,和之前几个生命周期中执行相似,流程就是 : ActivityThread.handleStopActivity() --> ActivityThread.performStopActivityInner() -(ActivityRecord.visible == false)-> ActivityThread.callActivityOnStop() --> Activity.performStop() --> Instrumentation.callActivityOnStop() --> Activity.onStop()

疑问:

  • 梳理完这五个生命周期,可以发现,只有在 ActivityRecord.visible 值为false,即Activity不可见的时候,才会进行 stop,那么这个visible的值究竟是在何处进行变化的呢?

    • 其实在解析整体流程时,我们能反复看到 ensureActivitiesVisibleLocked() 函数,从函数名称其实也可以看得出来,该函数中会进行Activity可见性的判断,那么接下来我们深入解析一下该函数,直接看 ActivityStack.ensureActivitiesVisibleLocked() 函数
  • ActivityStack.ensureActivitiesVisibleLocked()

    frameworks\base\services\core\java\com\android\server\am\ActivityStack.java

    final void ensureActivitiesVisibleLocked(ActivityRecord starting, int configChanges,
                                             boolean preserveWindows, boolean notifyClients) {
        ...
        try {
            // 拿到当前Stack最顶部的非finish状态的Activity
            ActivityRecord top = topRunningActivityLocked();
            ...
    
            //在top不为空的时候,aboveTop为true
            boolean aboveTop = top != null;
            // 判断当前的堆栈是否可见,如果可见则返回true
            final boolean stackShouldBeVisible = shouldBeVisible(starting);
            // 当前stack是否是被遮盖住的,和 stackShouldBeVisible 是相反的
            boolean behindFullscreenActivity = !stackShouldBeVisible;
            // 当 当前stack就是 mFocusedStack 并且 传入的 starting Activity 不在当前stack中,那么resumeNextActivity为true
            boolean resumeNextActivity = mStackSupervisor.isFocusedStack(this)
                && (isInStackLocked(starting) == null);
            // 如果当前Stack是有所属display的,并且对应display最上层的非pinnedWindow的stack就是当前的stack,那么isTopNotPinnedStack为true
            //代表当前的stack就是对应display上最顶层的非自由窗口的stack
            final boolean isTopNotPinnedStack = isAttached() && getDisplay().isTopNotPinnedStack(this);
            //开始从上向下遍历当前stack中的Activity
            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) {
                    final ActivityRecord r = activities.get(activityNdx);
                    //如果拿到的Activity是finish状态的,直接判断下一个
                    if (r.finishing) {
                        continue;
                    }
                    //判断当前获取到的Activity是否是topActivity,如果是则为 true
                    final boolean isTop = r == top;
                    //如果aboveTop是true 且 当前判断的Activity不是topActivity,直接判断下一个
                    if (aboveTop && !isTop) {
                        continue;
                    }
                    //将aboveTop置为false,代表不再受topActivity约束
                    aboveTop = false;
    
                    //忽略 keyguard 的情况下,是否可见
                    final boolean visibleIgnoringKeyguard = r.shouldBeVisibleIgnoringKeyguard(
                        behindFullscreenActivity);
                    r.visibleIgnoringKeyguard = visibleIgnoringKeyguard;
    
                    //判断当前遍历的Activity是否可见
                    final boolean reallyVisible = checkKeyguardVisibility(r,
                                                                          visibleIgnoringKeyguard, isTop && isTopNotPinnedStack);
                    //在判断上一个Activity忽略Keyguard时可见的情况下,需要再重新针对
                    //behindFullscreenActivity进行判断,关键就在此处
                    if (visibleIgnoringKeyguard) {
                        behindFullscreenActivity = updateBehindFullscreen(!stackShouldBeVisible,
                                                                          behindFullscreenActivity, r);
                    }
                    //如果是可见的
                    if (reallyVisible) {
                        ...
                    } else {
                        makeInvisible(r);
                    }
                }
                ...
            }
    
            ...
        }
        ...
    }
    
    • 略去相关性不大的代码,可以看到,与可见性判断呈直接关系的是如下的几个函数:

      • shouldBeVisible()
      • shouldBeVisibleIgnoringKeyguard()
      • checkKeyguardVisibility()
      • updateBehindFullscreen()

      我们假定一个场景,当前就是在判断 mFocusedStack ,且当前待启动的Activity是不透明的,且假定对应stack中只存在两个Activity对象,那么判断顺序如下:

    1. ActivityStack.shouldBeVisible()

      // 判断该堆栈是否可见,如果可见则返回true
      boolean shouldBeVisible(ActivityRecord starting) {
          //如果当前的stack没有所属的display 或者是 设置了强制隐藏,命中if
          //直接返回false,代表不可见
          if (!isAttached() || mForceHidden) {
              return false;
          }
          //如果判断的当前stack就是mFocusedStack,那么直接返回true,代表可见
          if (mStackSupervisor.isFocusedStack(this)) {
              return true;
          }
      
          //拿到当前stack最顶部的不为finish状态的Activity
          final ActivityRecord top = topRunningActivityLocked();
          //如果拿不到top,并且传入的Activity不在当前Stack中 并且 当前的stack不是所属的display最顶层的stack,命中if
          //直接返回false,代表不可见
          if (top == null && isInStackLocked(starting) == null && !isTopStackOnDisplay()) {
              return false;
          }
      
          //拿到所属的display
          final ActivityDisplay display = getDisplay();
          //是否有不透明的分屏stack
          boolean gotSplitScreenStack = false;
          //是否是不透明的主分屏stack
          boolean gotOpaqueSplitScreenPrimary = false;
          //是否是不透明的副分屏stack
          boolean gotOpaqueSplitScreenSecondary = false;
          //拿到当前的stack的windowMode
          final int windowingMode = getWindowingMode();
          //判断当前的Stack是否是ACTIVITY_TYPE_ASSISTANT类型
          final boolean isAssistantType = isActivityTypeAssistant();
          //从上往下遍历对应display中的所有ActivityStack
          for (int i = display.getChildCount() - 1; i >= 0; --i) {
              final ActivityStack other = display.getChildAt(i);
              //如果该display中存在当前的stack,那么直接返回true,代表可见
              if (other == this) {
                  return true;
              }
      
              //拿到当前遍历的stack的windowModevisible
              final int otherWindowingMode = other.getWindowingMode();
      
              //如果当前遍历的stack是 WINDOWING_MODE_FULLSCREEN 类型,那么只有在当前Stack是 WINDOWING_MODE_SPLIT_SCREEN_PRIMARY
              //类型并且 遍历的stack是ACTIVITY_TYPE_HOME 或者 是 ACTIVITY_TYPE_ASSISTANT类型且mRecentsAnimationController不为空
              //时才可见
              if (otherWindowingMode == WINDOWING_MODE_FULLSCREEN) {
                  final int activityType = other.getActivityType();
                  if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
                      if (activityType == ACTIVITY_TYPE_HOME
                          || (activityType == ACTIVITY_TYPE_ASSISTANT
                              && mWindowManager.getRecentsAnimationController() != null)) {
                          return true;
                      }
                  }
                  //如果判断的stack是透明的,那么继续判断下一个
                  if (other.isStackTranslucent(starting)) {
                      // Can be visible behind a translucent fullscreen stack.
                      continue;
                  }
                  return false;
                  //如果遍历的stack是主分屏stack,且尚不存在不透明的分屏主窗口,命中if
                  //那么如果判断other Stack是不透明的stack,且当前的stack是分屏主窗口类型,直接返回false,不可见
              } else if (otherWindowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY
                         && !gotOpaqueSplitScreenPrimary) {
                  gotSplitScreenStack = true;
                  gotOpaqueSplitScreenPrimary = !other.isStackTranslucent(starting);
                  if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY
                      && gotOpaqueSplitScreenPrimary) {
                      return false;
                  }
                  //与主分屏同理,判断副分屏的情况
              } else if (otherWindowingMode == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY
                         && !gotOpaqueSplitScreenSecondary) {
                  gotSplitScreenStack = true;
                  gotOpaqueSplitScreenSecondary = !other.isStackTranslucent(starting);
                  if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY
                      && gotOpaqueSplitScreenSecondary) {
                      return false;
                  }
              }
              //当主副分屏窗口都不透明时,直接返回false,不可见
              if (gotOpaqueSplitScreenPrimary && gotOpaqueSplitScreenSecondary) {
                  return false;
              }
              //如果当前的Stack是ACTIVITY_TYPE_ASSISTANT类型 并且 display中存在不透明的stack,直接返回false,不可见
              if (isAssistantType && gotSplitScreenStack) {
                  return false;
              }
          }
      
          //默认就是返回true,可见
          return true;
      }
      
      • 首先判断当前stack是否是可见,根据我们假设的前提,当前stack就是 mFocusedStack ,此处判断出来是可见的,即当前 stackShouldBeVisible = true,而 behindFullscreenActivity = false
    2. ActivityRecord.shouldBeVisibleIgnoringKeyguard(false)

      boolean shouldBeVisibleIgnoringKeyguard(boolean behindFullscreenActivity) {
          //判断当前Activity是否是可展示的
          if (!okToShowLocked()) {
              return false;
          }
      
          //根据传入的behindFullscreenActivity值或者mLaunchTaskBehind判断是否可见
          return !behindFullscreenActivity || mLaunchTaskBehind;
      }
      
      • 可以看到,在 shouldBeVisibleIgnoringKeyguard() 中,确保Activity可展示的前提下,会根据 传入的 behindFullscreenActivity 或者 mLaunchTaskBehind 来确定是否可见,而我们当下传入的 behindFullscreenActivity = false,所以此时肯定返回的是true,即 visibleIgnoringKeyguard = true
    3. ActivityStack.checkKeyguardVisibility(r, true, true)

      // 结合当前是否是锁屏状态,判断Activity可见性
      boolean checkKeyguardVisibility(ActivityRecord r, boolean shouldBeVisible, boolean isTop) {
          final int displayId = mDisplayId != INVALID_DISPLAY ? mDisplayId : DEFAULT_DISPLAY;
          //判断熄屏显示或者锁屏显示的状态
          final boolean keyguardOrAodShowing = mStackSupervisor.getKeyguardController()
              .isKeyguardOrAodShowing(displayId);
          //判断现在是不是锁屏显示的状态
          final boolean keyguardLocked = mStackSupervisor.getKeyguardController().isKeyguardLocked();
          //判断传入的Activity是否可以在锁屏状态进行显示
          final boolean showWhenLocked = r.canShowWhenLocked();
          //判断传入的Activity是否存在FLAG_DISMISS_KEYGUARD的window
          final boolean dismissKeyguard = r.hasDismissKeyguardWindows();
          //如果传入的shouldBeVisible为true,代表不考虑keyguard的时候可以显示,命中if
          //那么就去判断当前display是否有FLAG_CAN_SHOW_WITH_INSECURE_KEYGUARD标识,并且当前的锁屏可以不用凭证直接解除,
          //满足上述条件直接返回true,代表可见
          if (shouldBeVisible) {
              if (dismissKeyguard && mTopDismissingKeyguardActivity == null) {
                  mTopDismissingKeyguardActivity = r;
              }
      
              if (isTop) {
                  mTopActivityOccludesKeyguard |= showWhenLocked;
              }
      
              //判断当前stack所属的display是否有FLAG_CAN_SHOW_WITH_INSECURE_KEYGUARD标识
              final boolean canShowWithKeyguard = canShowWithInsecureKeyguard()
                  && mStackSupervisor.getKeyguardController().canDismissKeyguard(); //是否可以不输入凭证的情况下接触锁屏
              //如果所属display有FLAG_CAN_SHOW_WITH_INSECURE_KEYGUARD标识,并且不用密码就可以解除锁屏,直接返回true,代表可以显示
              if (canShowWithKeyguard) {
                  return true;
              }
          }
          //显示锁屏或者AOD时,命中if
          //只有在当前Activity可以解除锁屏,并且AOD不可见的时候才可见,即返回true
          if (keyguardOrAodShowing) {
              return shouldBeVisible && mStackSupervisor.getKeyguardController()
                  .canShowActivityWhileKeyguardShowing(r, dismissKeyguard);
           //显示锁屏时,命中else if
          //判断当前是否可以覆盖keyguard进行显示,是则返回true
          } else if (keyguardLocked) {
              return shouldBeVisible && mStackSupervisor.getKeyguardController().canShowWhileOccluded(
                  dismissKeyguard, showWhenLocked);
          //既没有锁屏也没有AOD,直接返回shouldBeVisible,即不考虑keyguard时的可见性即可
          } else {
              return shouldBeVisible;
          }
      }
      
      • 在该函数中,会根据是否显示 keyguard 或者 AOD 来判断该Activity是否真的可见,如果当前没有显示 keyguard 或者 AOD,那么就直接以传入的 shouldBeVisible 为准,此时就是直接返回 shouldBeVisible ,也就是 reallyVisible?=?true
    4. ActivityStack.updateBehindFullscreen(false, false, r)

      private boolean updateBehindFullscreen(boolean stackInvisible, boolean behindFullscreenActivity,
                                             ActivityRecord r) {
          //根据传入的Activity是否全屏显示,来决定behindFullscreenActivity的值
          if (r.fullscreen) {
              behindFullscreenActivity = true;
          }
          return behindFullscreenActivity;
      }
      
      • 可以看到,如果前一个传入的Activity是fullscreen的,即全屏显示的,那么就会设置behindFullscreenActivity = true,即代表在该Activity下面的Activity都是处于被盖住显示的状态
      • 针对当前的Activity,reallyVisible = true也就是可见的,那么在 ensureActivitiesVisibleLocked()函数中,会命中 if (reallyVisible){...} ,接下来会循环判断下一个 Activity 的可见性,此时 behindFullscreenActivity 是为 true
    5. ActivityRecord.shouldBeVisibleIgnoringKeyguard(true)

      • 由于此时传入的 behindFullscreenActivity 是为 true,进入判断后返回则为false,即 visibleIgnoringKeyguard = false
    6. ActivityStack.checkKeyguardVisibility(r, false, false)

      • 由于此时传入的 visibleIgnoringKeyguard = false,所以此时判断返回的 reallyVisible = false,即当前的Activity是不可见的,那么接下来就会命中 makeInvisible(r) ,也就会设置当前的 Activity 为 Invisible,并且在这之中,还会根据当前Activity的状态,决定是否将其添加到 mStoppingActivities 列表中,方便后续进行stopActivity
  移动开发 最新文章
Vue3装载axios和element-ui
android adb cmd
【xcode】Xcode常用快捷键与技巧
Android开发中的线程池使用
Java 和 Android 的 Base64
Android 测试文字编码格式
微信小程序支付
安卓权限记录
知乎之自动养号
【Android Jetpack】DataStore
上一篇文章      下一篇文章      查看所有文章
加:2022-06-29 19:12:58  更:2022-06-29 19:15:37 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/25 4:04:46-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码