Android | 基于Android9.0的startActivity流程分析(3):新Activity的onStart流程、onResume流程

目录

3. 新Activity的onStart流程

4. 新Activity的onResume流程

4.1 ResumeActivityItem.execute

4.2 ActivityThread.handleResumeActivity

4.2.1 ActivityThread.performResumeActivity

4.2.2 Looper.myQueue().addIdleHandler(new Idler())

4.3 ResumeActivityItem.postExecute


在上篇文章Android | 基于Android9.0的startActivity流程分析(2):新Activity的onCreate流程的末尾,说到了TransactionExecutor中的executeLifecycleState函数。该函数与onStart流程紧密相关,本篇文章从该函数入手,开始分析onStart流程。

3. 新Activity的onStart流程

先来看看TransactionExecutor.executeLifecycleState函数的源码重温一下:

// /frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java
     /** Transition to the final state if requested by the transaction. */
    private void executeLifecycleState(ClientTransaction transaction) {
        final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
        if (lifecycleItem == null) {
            // No lifecycle request, return early.
            return;
        }
        log("Resolving lifecycle state: " + lifecycleItem);
 
        final IBinder token = transaction.getActivityToken();
        final ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
 
        if (r == null) {
            // Ignore requests for non-existent client records for now.
            return;
        }
 
        // Cycle to the state right before the final requested state.
        cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */);
 
        // Execute the final transition with proper parameters.
        lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
        lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
    }

我们上篇文章说到,此处的lifecycleItem指的其实就是ResumeActivityItem,所以这个函数里执行的操作是:

  • TransactionExecutor.cycleToPath
  • ResumeActivityItem.execute:与onResume流程相关
  • ResumeActivityItem.postExecute

(1)先来看看TransactionExecutor.cycleToPath函数

// /frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java    
    /**
     * Transition the client between states with an option not to perform the last hop in the
     * sequence. This is used when resolving lifecycle state request, when the last transition must
     * be performed with some specific parameters.
     */
    private void cycleToPath(ActivityClientRecord r, int finish,
            boolean excludeLastState) {
        final int start = r.getLifecycleState();
        log("Cycle from: " + start + " to: " + finish + " excludeLastState:" + excludeLastState);
        final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
        performLifecycleSequence(r, path);
    }

可以看到,这里调用了performLifecycleSequence函数:

// /frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java    
    /** Transition the client through previously initialized state sequence. */
    private void performLifecycleSequence(ActivityClientRecord r, IntArray path) {
        final int size = path.size(); //此处的size = 1
        for (int i = 0, state; i < size; i++) {
            state = path.get(i); //state = 2,执行ON_START 的case
            log("Transitioning to state: " + state);
            switch (state) {
                case ON_CREATE:
                    mTransactionHandler.handleLaunchActivity(r, mPendingActions,
                            null /* customIntent */);
                    break;
                case ON_START:
                    mTransactionHandler.handleStartActivity(r, mPendingActions); //调用ActivityThread.handleStartActivity
                    break;
                case ON_RESUME:
                    mTransactionHandler.handleResumeActivity(r.token, false /* finalStateRequest */,
                            r.isForward, "LIFECYCLER_RESUME_ACTIVITY");
                    break;
                case ON_PAUSE:
                    mTransactionHandler.handlePauseActivity(r.token, false /* finished */,
                            false /* userLeaving */, 0 /* configChanges */, mPendingActions,
                            "LIFECYCLER_PAUSE_ACTIVITY");
                    break;
                case ON_STOP:
                    mTransactionHandler.handleStopActivity(r.token, false /* show */,
                            0 /* configChanges */, mPendingActions, false /* finalStateRequest */,
                            "LIFECYCLER_STOP_ACTIVITY");
                    break;
                case ON_DESTROY:
                    mTransactionHandler.handleDestroyActivity(r.token, false /* finishing */,
                            0 /* configChanges */, false /* getNonConfigInstance */,
                            "performLifecycleSequence. cycling to:" + path.get(size - 1));
                    break;
                case ON_RESTART:
                    mTransactionHandler.performRestartActivity(r.token, false /* start */);
                    break;
                default:
                    throw new IllegalArgumentException("Unexpected lifecycle state: " + state);
            }
        }
    }

接着来看看ActivityThread.handleStartActivity函数:

// /frameworks/base/core/java/android/app/ActivityThread.java	
    @Override
    public void handleStartActivity(ActivityClientRecord r,
            PendingTransactionActions pendingActions) {
        final Activity activity = r.activity;
        if (r.activity == null) {
            // TODO(lifecycler): What do we do in this case?
            return;
        }
        if (!r.stopped) {
            throw new IllegalStateException("Can't start activity that is not stopped.");
        }
        if (r.activity.mFinished) {
            // TODO(lifecycler): How can this happen?
            return;
        }

        // Start
        activity.performStart("handleStartActivity"); //执行Activity的performStart函数
        r.setState(ON_START);//将Activity状态设置为ON_START

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

        // Restore instance state
        if (pendingActions.shouldRestoreInstanceState()) { //pendingActions.shouldRestoreInstanceState()值为true
            if (r.isPersistable()) { //r.isPersistable()值为false
                if (r.state != null || r.persistentState != null) {
                    mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
                            r.persistentState);
                }
            } else if (r.state != null) {//r.state值为null
                mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
            }
        }

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

主要完成的操作:

  • Activity.performStart
  • Instrumetation.callActivityOnPostCreate

先看Activity.performStart:

// /frameworks/base/core/java/android/app/Activity.java    
    final void performStart(String reason) {
        mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
        mFragments.noteStateNotSaved();
        mCalled = false;
        mFragments.execPendingActions();
        mInstrumentation.callActivityOnStart(this); //调用Instrumentation.callActivityOnStart
        writeEventLog(LOG_AM_ON_START_CALLED, reason);

        if (!mCalled) {
            throw new SuperNotCalledException(
                "Activity " + mComponent.toShortString() +
                " did not call through to super.onStart()");
        }
        mFragments.dispatchStart(); //Fragment的start操作
        mFragments.reportLoaderStart();

        boolean isAppDebuggable =
                (mApplication.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;

        // This property is set for all non-user builds except final release
        boolean isDlwarningEnabled = SystemProperties.getInt("ro.bionic.ld.warning", 0) == 1;

        ...
        mActivityTransitionState.enterReady(this);
    }

调用了Instrumentation.callActivityOnStart函数:

// /frameworks/base/core/java/android/app/Instrumentation.java    
    /**
     * Perform calling of an activity's {@link Activity#onStart}
     * method.  The default implementation simply calls through to that method.
     *
     * @param activity The activity being started.
     */
    public void callActivityOnStart(Activity activity) {
        activity.onStart();
    }

至此,Activity的onStart被调用。

再来看看Instrumentation.callActivityOnPostCreate:

//  /frameworks/base/core/java/android/app/Instrumentation.java
    /**
     * Perform calling of an activity's {@link Activity#onPostCreate} method.
     * The default implementation simply calls through to that method.
     *
     * @param activity The activity being created.
     * @param icicle The previously frozen state (or null) to pass through to
     *               onPostCreate().
     */
    public void callActivityOnPostCreate(Activity activity, Bundle icicle) {
        activity.onPostCreate(icicle);
    }

调用了Activity.onPostCreate:

// /frameworks/base/core/java/android/app/Activity.java
    /**
     * Called when activity start-up is complete (after {@link #onStart}
     * and {@link #onRestoreInstanceState} have been called).  Applications will
     * generally not implement this method; it is intended for system
     * classes to do final initialization after application code has run.
     *
     * 

Derived classes must call through to the super class's * implementation of this method. If they do not, an exception will be * thrown.

* * @param savedInstanceState If the activity is being re-initialized after * previously being shut down then this Bundle contains the data it most * recently supplied in {@link #onSaveInstanceState}. Note: Otherwise it is null. * @see #onCreate */ @CallSuper protected void onPostCreate(@Nullable Bundle savedInstanceState) { if (!isChild()) { mTitleReady = true; onTitleChanged(getTitle(), getTitleColor()); //更新title } mCalled = true; } protected void onTitleChanged(CharSequence title, int color) { if (mTitleReady) { final Window win = getWindow(); if (win != null) { win.setTitle(title); if (color != 0) { win.setTitleColor(color); } } if (mActionBar != null) { mActionBar.setWindowTitle(title); } } }

同样的,来个思维导图回顾一下onStart流程,该图接着onCreate的流程(该图在跨进程时有一个问题,不过不妨碍流程回顾,更准确的图请看后面的思维导图)。

 

Android | 基于Android9.0的startActivity流程分析(3):新Activity的onStart流程、onResume流程_第1张图片


4. 新Activity的onResume流程

紧接上文,上文分析了TransactionExecutor.executeLifecycleState函数里执行了如下三个操作:

  • TransactionExecutor.cycleToPath
  • ResumeActivityItem.execute:与onResume流程相关
  • ResumeActivityItem.postExecute

其中仅分析了cycleToPath函数,接下来看看ResumeActivityItem.execute函数。

4.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");
        client.handleResumeActivity(token, true /* finalStateRequest */, mIsForward,
                "RESUME_ACTIVITY");
        Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
    }

同样地调用到了ActivityThread.handleResumeActivity。

4.2 ActivityThread.handleResumeActivity

// /frameworks/base/core/java/android/app/ActivityThread.java
	@Override
    public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
            String reason) {
        // If we are getting ready to gc after going to the background, well
        // we are back active so skip it.
        unscheduleGcIdler();
        ...

        // TODO Push resumeArgs into the activity for consideration
        final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
        if (r == null) {
            // We didn't actually resume the activity, so skipping any follow-up actions.
            return;
        }

        ...

        // If the window hasn't yet been added to the window manager,
        // and this guy didn't finish itself or start another activity,
        // then go ahead and add the window.
        boolean willBeVisible = !a.mStartedActivity; //结果为true
        
        ...
		
        // Get rid of anything left hanging around.
        cleanUpPendingRemoveWindows(r, false /* force */);

        // The window is now visible if it has been added, we are not
        // simply finishing, and we are not starting another activity.
		//r.activity.mFinished=false; willBeVisible=true; r.activity.mDecor=DecorView@36c7de6[SecondActivity]; r.hideForNow=false
        if (!r.activity.mFinished && willBeVisible && r.activity.mDecor != null && !r.hideForNow) { 
            if (r.newConfig != null) {   //r.newConfig 值为 null
                ...
            }
			
            ...
			
        }

        ...
        if (localLOGV) Slog.v(TAG, "Scheduling idle handler for " + r);
        Looper.myQueue().addIdleHandler(new Idler()); //消息队列里没有消息时执行Idler中的queueIdler
    }	

可以看到,主要的操作:

  1. ActivityThread.performResumeActivity
  2. ActivityThread.cleanUpPendingRemoveWindos
  3. Looper.myQueue().addIdleHandler(new Idler()):主线程的消息循环为空时执行

4.2.1 ActivityThread.performResumeActivity

先来看看performResumeActivity:

// /frameworks/base/core/java/android/app/ActivityThread.java
	/**
     * Resume the activity.
     * @param token Target activity token.
     * @param finalStateRequest Flag indicating if this is part of final state resolution for a
     *                          transaction.
     * @param reason Reason for performing the action.
     *
     * @return The {@link ActivityClientRecord} that was resumed, {@code null} otherwise.
     */
    @VisibleForTesting
    public ActivityClientRecord performResumeActivity(IBinder token, boolean finalStateRequest,
            String reason) {
        final ActivityClientRecord r = mActivities.get(token);
        if (localLOGV) {
            Slog.v(TAG, "Performing resume of " + r + " finished=" + r.activity.mFinished);
        }
        if (r == null || r.activity.mFinished) {
            return null;
        }
        if (r.getLifecycleState() == ON_RESUME) {  //此时Activity的状态为ON_START,所以不执行
            ...
            return null;
        }
        if (finalStateRequest) { //该值为true
            r.hideForNow = false;
            r.activity.mStartedActivity = false;
        }
        try {
            r.activity.onStateNotSaved();
            r.activity.mFragments.noteStateNotSaved(); 
            checkAndBlockForNetworkAccess();
            if (r.pendingIntents != null) { //r.pendingIntents值为null
                deliverNewIntents(r, r.pendingIntents);
                r.pendingIntents = null;
            }
            if (r.pendingResults != null) {//r.pendingResults值为null
                deliverResults(r, r.pendingResults, reason);
                r.pendingResults = null;
            }
            r.activity.performResume(r.startsNotResumed, reason); //【调用activity.performResume执行resume流程】

            r.state = null;
            r.persistentState = null;
            r.setState(ON_RESUME); //设置Activity的状态为ON_RESUME
        } catch (Exception e) {
            if (!mInstrumentation.onException(r.activity, e)) {
                throw new RuntimeException("Unable to resume activity "
                        + r.intent.getComponent().toShortString() + ": " + e.toString(), e);
            }
        }
        return r;
    }

可见主要完成的操作是调用Activity.performResume函数:

// /frameworks/base/core/java/android/app/Activity.java
    final void performResume(boolean followedByPause, String reason) {
        performRestart(true /* start */, reason); //该函数中因为mStopped = false,所以实际没有什么操作
 
        mFragments.execPendingActions(); //Fragment相关的操作

        mLastNonConfigurationInstances = null;

        if (mAutoFillResetNeeded) { //自动填充
            // When Activity is destroyed in paused state, and relaunch activity, there will be
            // extra onResume and onPause event,  ignore the first onResume and onPause.
            // see ActivityThread.handleRelaunchActivity()
            mAutoFillIgnoreFirstResumePause = followedByPause;
            if (mAutoFillIgnoreFirstResumePause && DEBUG_LIFECYCLE) {
                Slog.v(TAG, "autofill will ignore first pause when relaunching " + this);
            }
        }

        mCalled = false;
        // mResumed is set by the instrumentation
        mInstrumentation.callActivityOnResume(this);  //【调用Instrumentation.callActivityOnResume执行onResume流程】
		
        ...

        mFragments.dispatchResume(); //Fragment相关的操作
        mFragments.execPendingActions();//Fragment相关的操作

        onPostResume();
		
        ...
    }

可见,调用了Instrumentation.callActivityOnResume函数:

// /frameworks/base/core/java/android/app/Instrumentation.java    
    /**
     * Perform calling of an activity's {@link Activity#onResume} method.  The
     * default implementation simply calls through to that method.
     *
     * @param activity The activity being resumed.
     */
    public void callActivityOnResume(Activity activity) {
        activity.mResumed = true;
        activity.onResume();  //调用Activity的onResume函数

        if (mActivityMonitors != null) {
            synchronized (mSync) {
                final int N = mActivityMonitors.size();
                for (int i=0; i

至此,Activity的onResume函数被调用了。

4.2.2 Looper.myQueue().addIdleHandler(new Idler())

在主线程的消息循环中没有消息时,执行Idler中的函数queueIdle,运行于应用进程的主线程。该函数的调用堆栈:

D ActivityThread: Idler:queueIdle
D ActivityThread: java.lang.Throwable
D ActivityThread: 	at android.app.ActivityThread$Idler.queueIdle(ActivityThread.java:1866)
D ActivityThread: 	at android.os.MessageQueue.next(MessageQueue.java:395)
D ActivityThread: 	at android.os.Looper.loop(Looper.java:160)
D ActivityThread: 	at android.app.ActivityThread.main(ActivityThread.java:6833)
D ActivityThread: 	at java.lang.reflect.Method.invoke(Native Method)
D ActivityThread: 	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
D ActivityThread: 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:911)

先看Looper.myQueue():

// /frameworks/base/core/java/android/os/Looper.java

     /**
     * Return the {@link MessageQueue} object associated with the current
     * thread.  This must be called from a thread running a Looper, or a
     * NullPointerException will be thrown.
     */
    public static @NonNull MessageQueue myQueue() {
        return myLooper().mQueue;
    }
    
    /**
     * Return the Looper object associated with the current thread.  Returns
     * null if the calling thread is not associated with a Looper.
     */
    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

即addIdleHandler实质是调用的MessageQueue.addIdleHandler函数:

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

    private final ArrayList mIdleHandlers = new ArrayList();

     /**
     * Add a new {@link IdleHandler} to this message queue.  This may be
     * removed automatically for you by returning false from
     * {@link IdleHandler#queueIdle IdleHandler.queueIdle()} when it is
     * invoked, or explicitly removing it with {@link #removeIdleHandler}.
     *
     * 

This method is safe to call from any thread. * * @param handler The IdleHandler to be added. */ public void addIdleHandler(@NonNull IdleHandler handler) { if (handler == null) { throw new NullPointerException("Can't add a null IdleHandler"); } synchronized (this) { mIdleHandlers.add(handler); //将new 出来的Idler添加到mIdleHandlers中 } }

现在再来看看queueIdle函数的源码:

 private class Idler implements MessageQueue.IdleHandler {
        @Override
        public final boolean queueIdle() {
            ActivityClientRecord a = mNewActivities;
            boolean stopProfiling = false;
            if (mBoundApplication != null && mProfiler.profileFd != null
                    && mProfiler.autoStopProfiler) {
                stopProfiling = true;
            }
            if (a != null) {
                mNewActivities = null;
                IActivityManager am = ActivityManager.getService();
                ActivityClientRecord prev;
                do {
                    if (localLOGV) Slog.v(
                        TAG, "Reporting idle of " + a +
                        " finished=" +
                        (a.activity != null && a.activity.mFinished));
                    if (a.activity != null && !a.activity.mFinished) {
                        try {
                            am.activityIdle(a.token, a.createdConfig, stopProfiling); //跨进程调用AMS.activityIdle函数
                            a.createdConfig = null;
                        } catch (RemoteException ex) {
                            throw ex.rethrowFromSystemServer();
                        }
                    }
                    prev = a;
                    a = a.nextIdle;
                    prev.nextIdle = null;
                } while (a != null);
            }
            if (stopProfiling) {
                mProfiler.stopProfiling();
            }
            ensureJitEnabled();
            return false;
        }
    }

跨进程调用了AMS.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) {
            ActivityStack stack = ActivityRecord.getStackLocked(token);
            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);
    }

调用了ActivityStackSupervisor.activityIdleInternalLocked函数:

//  /frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java	
    // Checked.
    @GuardedBy("mService")
    final ActivityRecord activityIdleInternalLocked(final IBinder token, boolean fromTimeout,
            boolean processPausingActivities, Configuration config) {
        if (DEBUG_ALL) Slog.v(TAG, "Activity idle: " + token);

        ArrayList finishes = null;
        ArrayList startingUsers = null;
        int NS = 0;
        int NF = 0;
        boolean booting = false;
        boolean activityRemoved = false;

        ActivityRecord r = ActivityRecord.forTokenLocked(token);
        if (r != null) { //r 为新启动的Activity
            if (DEBUG_IDLE) Slog.d(TAG_IDLE, "activityIdleInternalLocked: Callers="
                    + Debug.getCallers(4));
            mHandler.removeMessages(IDLE_TIMEOUT_MSG, r); //remove IDLE_TIMEOUT_MSG消息
            r.finishLaunchTickingLocked();
            if (fromTimeout) { //值为false
                reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
            }

            // This is a hack to semi-deal with a race condition
            // in the client where it can be constructed with a
            // newer configuration from when we asked it to launch.
            // We'll update with whatever configuration it now says
            // it used to launch.
            if (config != null) { //config不为空
                r.setLastReportedGlobalConfiguration(config);
            }

            // We are now idle.  If someone is waiting for a thumbnail from
            // us, we can now deliver.
            r.idle = true;

            //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
            if (isFocusedStack(r.getStack()) || fromTimeout) {
                booting = checkFinishBootingLocked();
            }
        }

        if (allResumedActivitiesIdle()) { //【1】检测是否所有的resumed activity 都是idle状态
            if (r != null) {
                mService.scheduleAppGcsLocked();
            }

            if (mLaunchingActivity.isHeld()) { //结果为true,因为持有了WakeLock
                mHandler.removeMessages(LAUNCH_TIMEOUT_MSG); //移除LAUNCH_TIMEOUT_MSG
                if (VALIDATE_WAKE_LOCK_CALLER &&
                        Binder.getCallingUid() != Process.myUid()) {
                    throw new IllegalStateException("Calling must be system uid");
                }
                mLaunchingActivity.release();
            }
            ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
        }

        // Atomically retrieve all of the other things to do.
        final ArrayList stops = processStoppingActivitiesLocked(r,
                true /* remove */, processPausingActivities); //【2】获取stopping的activity
        NS = stops != null ? stops.size() : 0;
        if ((NF = mFinishingActivities.size()) > 0) { //mFinishingActivities.size()=0
            finishes = new ArrayList<>(mFinishingActivities);
            mFinishingActivities.clear();
        }

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

        // Stop any activities that are scheduled to do so but have been
        // waiting for the next one to start.
        for (int i = 0; i < NS; i++) { //【3】NS=0,for循环不会执行
            r = stops.get(i);
            final ActivityStack stack = r.getStack();
            if (stack != null) {
                if (r.finishing) {
                    stack.finishCurrentActivityLocked(r, ActivityStack.FINISH_IMMEDIATELY, false,
                            "activityIdleInternalLocked");
                } else {
                    stack.stopActivityLocked(r);
                }
            }
        }

        // Finish any activities that are scheduled to do so but have been
        // waiting for the next one to start.
        for (int i = 0; i < NF; i++) { //【4】NF=0,for循环不会执行
            r = finishes.get(i);
            final ActivityStack stack = r.getStack();
            if (stack != null) {
                activityRemoved |= stack.destroyActivityLocked(r, true, "finish-idle");
            }
        }

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

        mService.trimApplications(); //调用AMS.trimApplications
        //dump();
        //mWindowManager.dump();

        if (activityRemoved) { //activityRemoved=false
            resumeFocusedStackTopActivityLocked();
        }

        return r;
    }

这个函数里有两个主要操作:

  • allResumedActivitiesIdle():是否所有resumed activity都是idle状态
  • processStoppingActivitiesLocked:获取stopping的activity
// /frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java
     boolean allResumedActivitiesIdle() {
        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
            final ActivityDisplay display = mActivityDisplays.valueAt(displayNdx);
            for (int stackNdx = display.getChildCount() - 1; stackNdx >= 0; --stackNdx) {
                final ActivityStack stack = display.getChildAt(stackNdx);
                if (!isFocusedStack(stack) || stack.numActivities() == 0) {
                    continue;
                }
                final ActivityRecord resumedActivity = stack.getResumedActivity(); //resumedActivity 为新启动的Activity
                if (resumedActivity == null || !resumedActivity.idle) { //if条件不满足
                    if (DEBUG_STATES) Slog.d(TAG_STATES, "allResumedActivitiesIdle: stack="
                             + stack.mStackId + " " + resumedActivity + " not idle");
                    return false;
                }
            }
        }
        // Send launch end powerhint when idle
        sendPowerHintForLaunchEndIfNeeded();
        return true; //返回true
    }
// /frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java
	final ArrayList processStoppingActivitiesLocked(ActivityRecord idleActivity,
            boolean remove, boolean processPausingActivities) {
        ArrayList stops = null;

        final boolean nowVisible = allResumedActivitiesVisible();
        for (int activityNdx = mStoppingActivities.size() - 1; activityNdx >= 0; --activityNdx) {
            ActivityRecord s = mStoppingActivities.get(activityNdx);
            boolean waitingVisible = mActivitiesWaitingForVisibleActivity.contains(s);
            if (DEBUG_STATES) Slog.v(TAG, "Stopping " + s + ": nowVisible=" + nowVisible
                    + " waitingVisible=" + waitingVisible + " finishing=" + s.finishing);
            if (waitingVisible && nowVisible) {
                mActivitiesWaitingForVisibleActivity.remove(s);
                waitingVisible = false;
                if (s.finishing) {
                    // If this activity is finishing, it is sitting on top of
                    // everyone else but we now know it is no longer needed...
                    // so get rid of it.  Otherwise, we need to go through the
                    // normal flow and hide it once we determine that it is
                    // hidden by the activities in front of it.
                    if (DEBUG_STATES) Slog.v(TAG, "Before stopping, can hide: " + s);
                    s.setVisibility(false);
                }
            }
            if (remove) {
                final ActivityStack stack = s.getStack();
                final boolean shouldSleepOrShutDown = stack != null
                        ? stack.shouldSleepOrShutDownActivities()
                        : mService.isSleepingOrShuttingDownLocked();
                if (!waitingVisible || shouldSleepOrShutDown) {
                    if (!processPausingActivities && s.isState(PAUSING)) {
                        // Defer processing pausing activities in this iteration and reschedule
                        // a delayed idle to reprocess it again
                        removeTimeoutsForActivityLocked(idleActivity);
                        scheduleIdleTimeoutLocked(idleActivity);
                        continue;
                    }

                    if (DEBUG_STATES) Slog.v(TAG, "Ready to stop: " + s);
                    if (stops == null) {
                        stops = new ArrayList<>();
                    }
                    stops.add(s);
                    mStoppingActivities.remove(activityNdx);
                }
            }
        }

        return stops;
    }

网上大部分的文章,在说到原Activity的onStop流程时,都说是从queueIdle函数中的如下代码块:

// Stop any activities that are scheduled to do so but have been
// waiting for the next one to start.
for (int i = 0; i < NS; i++) { //【3】NS=0,for循环不会执行
    r = stops.get(i);
    final ActivityStack stack = r.getStack();
    if (stack != null) {
        if (r.finishing) {
            stack.finishCurrentActivityLocked(r, ActivityStack.FINISH_IMMEDIATELY, false,
                "activityIdleInternalLocked");
        } else {
            stack.stopActivityLocked(r);
        }
    }
}

通过此处的ActivityStack.stopActivityLocked函数完成了原Activity的onStop流程。但是通过在源码中添加log确认,此时NS =0,该for循环并不会执行。所以onStop流程并不是从此处完成的。如果不对之处,欢迎指正。

此处上一个思维导图回顾流程:

Android | 基于Android9.0的startActivity流程分析(3):新Activity的onStart流程、onResume流程_第2张图片

4.3 ResumeActivityItem.postExecute

// /frameworks/base/core/java/android/app/servertransaction/ResumeActivityItem.java    
    @Override
    public void postExecute(ClientTransactionHandler client, IBinder token,
            PendingTransactionActions pendingActions) {
        try {
            // TODO(lifecycler): Use interface callback instead of AMS.
            ActivityManager.getService().activityResumed(token); //【跨进程调用到AMS.activityResumed】
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
    }

跨进程调用了AMS.activityResumed函数:

// /frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java  
  
    WindowManagerService mWindowManager;

    @Override
    public final void activityResumed(IBinder token) {
        final long origId = Binder.clearCallingIdentity();
        synchronized(this) {
            ActivityRecord.activityResumedLocked(token);
            mWindowManager.notifyAppResumedFinished(token);
        }
        Binder.restoreCallingIdentity(origId);
    }

该函数完成的操作:

  • ActivityRecord.activityResumedLocked
  • WMS.notifyAppResumedFinished

先看activityResumedLocked函数:

// /frameworks/base/core/java/android/app/ActivityRecord.java
static void activityResumedLocked(IBinder token) {
        final ActivityRecord r = ActivityRecord.forTokenLocked(token);
        if (DEBUG_SAVED_STATE) Slog.i(TAG_STATES, "Resumed activity; dropping state of: " + r);
        if (r != null) {
            r.icicle = null;
            r.haveState = false;
        }
    }

再看看WMS.notifyAppResumedFinished:

//  /frameworks/base/services/core/java/com/android/server/wm/WindowManagerService.java

    final UnknownAppVisibilityController mUnknownAppVisibilityController =
            new UnknownAppVisibilityController(this);

    public void notifyAppResumedFinished(IBinder token) {
        synchronized (mWindowMap) {
            final AppWindowToken appWindow = mRoot.getAppWindowToken(token);
            if (appWindow != null) {
                mUnknownAppVisibilityController.notifyAppResumedFinished(appWindow);
            }
        }
    }
// /frameworks/base/services/core/java/com/android/server/wm/UnknownAppVisibilityController.java    
    
    // Set of apps for which we don't know yet whether it's visible or not, depending on what kind
    // of lockscreen flags the app might set during its first relayout.
    private final ArrayMap mUnknownApps = new ArrayMap<>();

    /**
     * Notifies that {@param appWindow} has finished resuming.
     */
    void notifyAppResumedFinished(@NonNull AppWindowToken appWindow) {
        if (mUnknownApps.containsKey(appWindow)
                && mUnknownApps.get(appWindow) == UNKNOWN_STATE_WAITING_RESUME) {
            if (DEBUG_UNKNOWN_APP_VISIBILITY) {
                Slog.d(TAG, "App resume finished appWindow=" + appWindow);
            }
            mUnknownApps.put(appWindow, UNKNOWN_STATE_WAITING_RELAYOUT);
        }
    }

 

你可能感兴趣的:(#,Activity)