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.
     *
     * <p><em>Derived classes must call through to the super class's
     * implementation of this method.  If they do not, an exception will be
     * thrown.</em></p>
     *
     * @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}.  <b><i>Note: Otherwise it is null.</i></b>
     * @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的流程。

 


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<N; i++) {
                    final ActivityMonitor am = mActivityMonitors.get(i);
                    am.match(activity, activity, activity.getIntent());
                }
            }
        }
    }

至此,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<IdleHandler> mIdleHandlers = new ArrayList<IdleHandler>();

     /**
     * 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}.
     *
     * <p>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<ActivityRecord> finishes = null;
        ArrayList<UserState> startingUsers = null;
        int NS = 0;
        int NF = 0;
        boolean booting = false;
        boolean activityRemoved = false;

        ActivityRecord r = ActivityRecord.forTokenLocked(token);
        if (r != null) { //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<ActivityRecord> 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<ActivityRecord> processStoppingActivitiesLocked(ActivityRecord idleActivity,
            boolean remove, boolean processPausingActivities) {
        ArrayList<ActivityRecord> 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流程並不是從此處完成的。如果不對之處,歡迎指正。

此處補充一下更完整一些的思維導圖:

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<AppWindowToken, Integer> 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);
        }
    }

 

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