2019-03-01 9.0 activity 啟動流程源碼分析<2>

上一篇文章分析了activity 的第一個生命周期 onPause 方法,也就是 resumeTopActivityInnerLocked 方法里面的第一部分,接下來繼續(xù)分析剩下兩部分

第二部分:根據(jù)任務棧判斷是否直接調用 activity 的 onNewIntent 方法

回到 resumeTopActivityInnerLocked 方法中

    private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
        //......

        // 假如已經存在
        if (next.app != null && next.app.thread != null) {
           
                //.......

                try {
                    //使用 ClientTransaction 調度生命周期
                    final ClientTransaction transaction = ClientTransaction.obtain(next.app.thread,
                            next.appToken);
                     //......
                    //判斷 newIntents 的值是否存在,主要是判斷是否需要調用 onNewIntent 方法
                    //這個值在哪里賦值呢,后面分析
                    if (next.newIntents != null) {
                        transaction.addCallback(NewIntentItem.obtain(next.newIntents,
                                false /* andPause */));
                    }

                    // 執(zhí)行調度
                    mService.getLifecycleManager().scheduleTransaction(transaction);
            //......
        } 
    }

調用了 transaction.addCallback 方法,根據(jù)上一篇分析,當前 callback 有值所以調用 executeCallbacks 方法時

    public void executeCallbacks(ClientTransaction transaction) {
         //循環(huán) callbacks 
        final int size = callbacks.size();
        for (int i = 0; i < size; ++i) {
            //執(zhí)行 execute
            item.execute(mTransactionHandler, token, mPendingActions);
            item.postExecute(mTransactionHandler, token, mPendingActions);
        }
    }

根據(jù)前面,知道當前 item 是 NewIntentItem

    public void execute(ClientTransactionHandler client, IBinder token,
                        PendingTransactionActions pendingActions) {
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityNewIntent");
        //根據(jù)前面文章的分析知道 client 為 ClientTransactionHandler 的子類 ActivityThread
        client.handleNewIntent(token, mIntents, mPause);
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
    }

    // ActivityThread 類中
    public void handleNewIntent(IBinder token, List<ReferrerIntent> intents, boolean andPause) {
        performNewIntents(token, intents, andPause);
    }

    void performNewIntents(IBinder token, List<ReferrerIntent> intents, boolean andPause) {
        //判斷是否已經調用了 paused 方法
        final boolean resumed = !r.paused;
        if (resumed) {
            r.activity.mTemporaryPause = true;
            //沒有從新走一遍
            mInstrumentation.callActivityOnPause(r.activity);
        }
        checkAndBlockForNetworkAccess();
        //調用該方法
        deliverNewIntents(r, intents);
    }

     private void deliverNewIntents(ActivityClientRecord r, List<ReferrerIntent> intents) {
        final int N = intents.size();
        for (int i=0; i<N; i++) {
            ReferrerIntent intent = intents.get(i);
            intent.setExtrasClassLoader(r.activity.getClassLoader());
            intent.prepareToEnterProcess();
            r.activity.mFragments.noteStateNotSaved();
            //通過 mInstrumentation 調用 callActivityOnNewIntent 方法
            mInstrumentation.callActivityOnNewIntent(r.activity, intent);
        }
    }

    public void callActivityOnNewIntent(Activity activity, Intent intent) {
        //調用activity 的 performNewIntent 
        activity.performNewIntent(intent);
    }

    //activity 類中
    final void performNewIntent(Intent intent) {
        mCanEnterPictureInPicture = true;
        //調用 onNewIntent 方法
        onNewIntent(intent);
    }

最終會走到 activity 中的 onNewIntent 方法。所以當設置 activity 的一些啟動模式是,再次啟動不會重走一遍生命周期,而會走到 onNewIntent 方法中。

還有一個問題 next.newIntents 是在那里賦值,怎么判斷是否調用 onNewIntent 方法的呢?還記得前面分析的一個方法 startActivityUnchecked ,這個方法主要是用來判斷啟動的 activity 的啟動模式


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

             //......
            //判斷當前的啟動模式是否為 SINGLE_INSTANCE 或則 LAUNCH_SINGLE_TASK
            //這兩種分別對應 singleTask 和 singleInstance
            if ((mLaunchFlags & FLAG_ACTIVITY_CLEAR_TOP) != 0
                    || isDocumentLaunchesIntoExisting(mLaunchFlags)
                    || isLaunchModeOneOf(LAUNCH_SINGLE_INSTANCE, LAUNCH_SINGLE_TASK)) {
                final TaskRecord task = reusedActivity.getTask();

                //......
                if (top != null) {
                    if (top.frontOfTask) {
                        // Activity aliases may mean we use different intents for the top activity,
                        // so make sure the task now has the identity of the new intent.
                        top.getTask().setIntent(mStartActivity);
                    }
                     //調用該方法給 newIntents 賦值
                    deliverNewIntent(top);
                }
            }

        //......
        final ActivityStack topStack = mSupervisor.mFocusedStack;
        final ActivityRecord topFocused = topStack.getTopActivity();
        final ActivityRecord top = topStack.topRunningNonDelayedActivityLocked(mNotTop);
        //判斷當前啟動模式是否為 singleTop 并且要啟動的 activity 位于棧頂
        final boolean dontStart = top != null && mStartActivity.resultTo == null
                && top.realActivity.equals(mStartActivity.realActivity)
                && top.userId == mStartActivity.userId
                && top.app != null && top.app.thread != null
                && ((mLaunchFlags & FLAG_ACTIVITY_SINGLE_TOP) != 0
                || isLaunchModeOneOf(LAUNCH_SINGLE_TOP, LAUNCH_SINGLE_TASK));
        if (dontStart) {
            // For paranoia, make sure we have correctly resumed the top activity.
            topStack.mLastPausedActivity = null;
            if (mDoResume) {
                mSupervisor.resumeFocusedStackTopActivityLocked();
            }
            ActivityOptions.abort(mOptions);
            if ((mStartFlags & START_FLAG_ONLY_IF_NEEDED) != 0) {
                // We don't need to start a new activity, and the client said not to do
                // anything if that is the case, so this is it!
                return START_RETURN_INTENT_TO_CALLER;
            }
            //調用該方法
            deliverNewIntent(top);
        }
        //........

        int result = START_SUCCESS;
         //如果是NEW_TASK
        if (mStartActivity.resultTo == null && mInTask == null && !mAddingToTask
                && (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) {
            newTask = true;
            //新建task
            result = setTaskFromReuseOrCreateNewTask(taskToAffiliate, topStack);
        } else if (mSourceRecord != null) {
            result = setTaskFromSourceRecord();
        } else if (mInTask != null) {
            result = setTaskFromInTask();
        } else {
            // This not being started from an existing activity, and not part of a new task...
            // just put it in the top task, though these days this case should never happen.
            setTaskToCurrentTopOrCreateNewTask();
        }
        if (result != START_SUCCESS) {
            return result;
        }
        //.....
    }

    private void deliverNewIntent(ActivityRecord activity) {
        //....
        activity.deliverNewIntentLocked(mCallingUid, mStartActivity.intent,
                mStartActivity.launchedFromPackage);
        mIntentDelivered = true;
    }

    final void deliverNewIntentLocked(int callingUid, Intent intent, String referrer) {
        //......
        //判斷狀態(tài)是否為 resumed 或 paused 是就直接執(zhí)行 onNewIntent 方法
        if ((mState == RESUMED || mState == PAUSED
                || isTopActivityWhileSleeping) && app != null && app.thread != null) {
            try {
                ArrayList<ReferrerIntent> ar = new ArrayList<>(1);
                ar.add(rintent);
                //使用 LifecycleManager 調度生命周期
                service.getLifecycleManager().scheduleTransaction(app.thread, appToken,
                        NewIntentItem.obtain(ar, mState == PAUSED));
                unsent = false;
            } catch (RemoteException e) {
                Slog.w(TAG, "Exception thrown sending new intent to " + this, e);
            } catch (NullPointerException e) {
                Slog.w(TAG, "Exception thrown sending new intent to " + this, e);
            }
        }
        if (unsent) {
            //給前面說的 newIntents 賦值,再后面判斷是否調用 onNewIntent 方法
            addNewIntentLocked(rintent);
        }
    }

    private void addNewIntentLocked(ReferrerIntent intent) {
        if (newIntents == null) {
            newIntents = new ArrayList<>();
        }
        //add 進去
        newIntents.add(intent);
    }

從上面可以知道,通過判斷 activity 的啟動模式來判斷是否調用 deliverNewIntent 方法,從而調用 onNewIntent

第三部分:啟動一個新的 activity

繼續(xù)回到 resumeTopActivityInnerLocked 方法中

    private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
        //.......
        //判斷是否存在,前面已經分析了,現(xiàn)在分析不存在的部分
        if (next.app != null && next.app.thread != null) {
          //......
        } else {
            // Whoops, need to restart this activity!
            if (!next.hasBeenLaunched) {
                next.hasBeenLaunched = true;
            } else {
                if (SHOW_APP_STARTING_PREVIEW) {
                    next.showStartingWindow(null /* prev */, false /* newTask */,
                            false /* taskSwich */);
                }
                if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "Restarting: " + next);
            }
            if (DEBUG_STATES) Slog.d(TAG_STATES, "resumeTopActivityLocked: Restarting " + next);
            //不管前面的判斷,最后都會走到這里
            mStackSupervisor.startSpecificActivityLocked(next, true, true);
        }
    }

    void startSpecificActivityLocked(ActivityRecord r,
            boolean andResume, boolean checkConfig) {
      
        //判斷該 app 的進程和線程是否存在
        if (app != null && app.thread != null) {
            try {
                 //.....
                //假如存在,直接調用該方法
                //這個方法后面在來分析,先看進程
                realStartActivityLocked(r, app, andResume, checkConfig);
                return;
            } catch (RemoteException e) {
                Slog.w(TAG, "Exception when starting activity "
                        + r.intent.getComponent().flattenToShortString(), e);
            }

            // If a dead object exception was thrown -- fall through to
            // restart the application.
        }
        //當前啟動的 activity 沒有對應的進程
        mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
                "activity", r.intent.getComponent(), false, false, true);
    }

這里判斷當前需要啟動的 activity 進程和線程是否存在,先看不存在的情況

    final ProcessRecord startProcessLocked(String processName,
            ApplicationInfo info, boolean knownToBeDead, int intentFlags,
            String hostingType, ComponentName hostingName, boolean allowWhileBooting,
            boolean isolated, boolean keepIfLarge) {
        return startProcessLocked(processName, info, knownToBeDead, intentFlags, hostingType,
                hostingName, allowWhileBooting, isolated, 0 /* isolatedUid */, keepIfLarge,
                null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */,
                null /* crashHandler */);
    }

    final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
            boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName,
            boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge,
            String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) {
          //.....

        final boolean success = startProcessLocked(app, hostingType, hostingNameStr, abiOverride);
        //...
        return success ? app : null;
    }

    private final boolean startProcessLocked(ProcessRecord app,
            String hostingType, String hostingNameStr, String abiOverride) {
        return startProcessLocked(app, hostingType, hostingNameStr,
                false /* disableHiddenApiChecks */, abiOverride);
    }

    private final boolean startProcessLocked(ProcessRecord app, String hostingType,
            String hostingNameStr, boolean disableHiddenApiChecks, String abiOverride) {
        
            //.....
            //需要開啟的線程名稱
            final String entryPoint = "android.app.ActivityThread";

            return startProcessLocked(hostingType, hostingNameStr, entryPoint, app, uid, gids,
                    runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet, invokeWith,
                    startTime);
      
    }

private boolean startProcessLocked(String hostingType, String hostingNameStr, String entryPoint,
            ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
            String seInfo, String requiredAbi, String instructionSet, String invokeWith,
            long startTime) {
       
    //....
                    final ProcessStartResult startResult = startProcess(app.hostingType, entryPoint,
                          
    }

    private ProcessStartResult startProcess(String hostingType, String entryPoint,
            ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
            String seInfo, String requiredAbi, String instructionSet, String invokeWith,
            long startTime) {
       
                startResult = Process.start(entryPoint,
                        app.processName, uid, uid, gids, runtimeFlags, mountExternal,
                        app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
                        app.info.dataDir, invokeWith,
                        new String[] {PROC_START_SEQ_IDENT + app.startSeq});
          
    }

    public static final ProcessStartResult start(final String processClass,
                                  final String niceName,
                                  int uid, int gid, int[] gids,
                                  int runtimeFlags, int mountExternal,
                                  int targetSdkVersion,
                                  String seInfo,
                                  String abi,
                                  String instructionSet,
                                  String appDataDir,
                                  String invokeWith,
                                  String[] zygoteArgs) {
        return zygoteProcess.start(processClass, niceName, uid, gid, gids,
                    runtimeFlags, mountExternal, targetSdkVersion, seInfo,
                    abi, instructionSet, appDataDir, invokeWith, zygoteArgs);
    }

    public final Process.ProcessStartResult start(final String processClass,
                                                  final String niceName,
                                                  int uid, int gid, int[] gids,
                                                  int runtimeFlags, int mountExternal,
                                                  int targetSdkVersion,
                                                  String seInfo,
                                                  String abi,
                                                  String instructionSet,
                                                  String appDataDir,
                                                  String invokeWith,
                                                  String[] zygoteArgs) {
        try {
            return startViaZygote(processClass, niceName, uid, gid, gids,
                    runtimeFlags, mountExternal, targetSdkVersion, seInfo,
                    abi, instructionSet, appDataDir, invokeWith, false /* startChildZygote */,
                    zygoteArgs);
        } catch (ZygoteStartFailedEx ex) {
            Log.e(LOG_TAG,
                    "Starting VM process through Zygote failed");
            throw new RuntimeException(
                    "Starting VM process through Zygote failed", ex);
        }
    }
  
    private Process.ProcessStartResult startViaZygote(final String processClass,
                                                      final String niceName,
                                                      final int uid, final int gid,
                                                      final int[] gids,
                                                      int runtimeFlags, int mountExternal,
                                                      int targetSdkVersion,
                                                      String seInfo,
                                                      String abi,
                                                      String instructionSet,
                                                      String appDataDir,
                                                      String invokeWith,
                                                      boolean startChildZygote,
                                                      String[] extraArgs)
                                                      throws ZygoteStartFailedEx {

        synchronized(mLock) {
            return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote);
        }
    }

這一大段代碼主要是:通過 zygote fork 出一個進程再創(chuàng)建出一個 android.app.ActivityThread 線程,調用該線程的 main 方法,接下來看 ActivityThread 的 main 方法

    public static void main(String[] args) {
        //創(chuàng)建該線程的 looper 對象
        Looper.prepareMainLooper();

        ActivityThread thread = new ActivityThread();
        //調用 attach
        thread.attach(false, startSeq);


         //循環(huán)
        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

    private void attach(boolean system, long startSeq) {
        sCurrentActivityThread = this;
        mSystemThread = system;
        //根據(jù) main 方法中的值,當前 system 值為 false
        if (!system) {
           
            android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
                                                    UserHandle.myUserId());
            RuntimeInit.setApplicationObject(mAppThread.asBinder());
            //獲取當前的 ActivityManagerService
            final IActivityManager mgr = ActivityManager.getService();
            try {
                //注意 mAppThread 是 ApplicationThread 對象
                //主要作用是作為一個 service 端接收 ActivityManagerService 的消息
                mgr.attachApplication(mAppThread, startSeq);
            } catch (RemoteException ex) {
                throw ex.rethrowFromSystemServer();
            }
        } 
    }

    public final void attachApplication(IApplicationThread thread, long startSeq) {
        synchronized (this) {
             //獲取對應 ID
            int callingPid = Binder.getCallingPid();
            final int callingUid = Binder.getCallingUid();
            final long origId = Binder.clearCallingIdentity();
            //綁定 Application
            attachApplicationLocked(thread, callingPid, callingUid, startSeq);
            Binder.restoreCallingIdentity(origId);
        }
    }

    private final boolean attachApplicationLocked(IApplicationThread thread,
            int pid, int callingUid, long startSeq) {

            //......

                //創(chuàng)建 ContextImpl 對象
                //創(chuàng)建 mInstrumentation 實例
               //創(chuàng)建 Application 調用對應的 onCreate 方法
                //這里就不展開了
                thread.bindApplication(processName, appInfo, providers,
                        app.instr.mClass,
                        profilerInfo, app.instr.mArguments,
                        app.instr.mWatcher,
                        app.instr.mUiAutomationConnection, testMode,
                        mBinderTransactionTrackingEnabled, enableTrackAllocation,
                        isRestrictedBackupMode || !normalMode, app.persistent,
                        new Configuration(getGlobalConfiguration()), app.compat,
                        getCommonServicesLocked(app.isolated),
                        mCoreSettingsObserver.getCoreSettingsLocked(),
                        buildSerial, isAutofillCompatEnabled);
         
         //.....
        if (normalMode) {
            try {
                //啟動對應 activity 
                if (mStackSupervisor.attachApplicationLocked(app)) {
                    didSomething = true;
                }
            } catch (Exception e) {
                Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
                badApp = true;
            }
        }

    //....
    }

    boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
        final String processName = app.processName;
        boolean didSomething = false;
                            //調用 realStartActivityLocked 方法
                            if (realStartActivityLocked(activity, app,
                                    top == activity /* andResume */, true /* checkConfig */)) {
                                didSomething = true;
                            }
                      
        return didSomething;
    }

最后走了一圈,又回到了 realStartActivityLocked 方法,所以啟動 activity 不管進程有沒有存在,最終都會走到realStartActivityLocked 方法中

    final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
            boolean andResume, boolean checkConfig) throws RemoteException {

                //.....
                //使用 ClientTransaction 管理生命周期
                final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
                        r.appToken);
                //將 LaunchActivityItem 添加進去
                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));

                // 根據(jù)前面,可以知道 andResume 值為true
                final ActivityLifecycleItem lifecycleItem;
                if (andResume) {
                    lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
                } else {
                    lifecycleItem = PauseActivityItem.obtain();
                }
                //設置狀態(tài)
                clientTransaction.setLifecycleStateRequest(lifecycleItem);

                // 調度
                mService.getLifecycleManager().scheduleTransaction(clientTransaction);

    //....
    }

根據(jù)前面的分析,知道分別會調用 LaunchActivityItem.execute 方法和 ResumeActivityItem.execute 方法,先來看第一個

    // LaunchActivityItem 類中 execute 方法
    public void execute(ClientTransactionHandler client, IBinder token,
                        PendingTransactionActions pendingActions) {
        Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
        ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
                mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
                mPendingResults, mPendingNewIntents, mIsForward,
                mProfilerInfo, client);
        //調用 handleLaunchActivity 方法
        //通過之前的分析可以知道 client 為 ActivityThread
        client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
        Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
    }
    
    // ActivityThread 中
    public Activity handleLaunchActivity(ActivityClientRecord r,
            PendingTransactionActions pendingActions, Intent customIntent) {
       //.....

        final Activity a = performLaunchActivity(r, customIntent);

        //....

        return a;
    }

    //該方法通過反射創(chuàng)建對應的activity實例
    //調用該 activity 的onCreate 方法
    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        ActivityInfo aInfo = r.activityInfo;

        //獲取包名
        ComponentName component = r.intent.getComponent();

        //創(chuàng)建 ContextImpl 實例
        //這里可以知道 activity 中的 context 的實例為 ContextImpl
        ContextImpl appContext = createBaseContextForActivity(r);
        Activity activity = null;
        try {
            //獲取 ClassLoader
            java.lang.ClassLoader cl = appContext.getClassLoader();
            //反射生成 activity 對象
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
            StrictMode.incrementExpectedActivityCount(activity.getClass());
            r.intent.setExtrasClassLoader(cl);
            r.intent.prepareToEnterProcess();
            if (r.state != null) {
                r.state.setClassLoader(cl);
            }
        } catch (Exception e) {
            if (!mInstrumentation.onException(activity, e)) {
                throw new RuntimeException(
                    "Unable to instantiate activity " + component
                    + ": " + e.toString(), e);
            }
        }

        try {
                //....
                //初始化參數(shù)
                //關聯(lián)該 activity 和 context 
                //創(chuàng)建 PhoneWindow
                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);

                //調用activity 的 onCreate 方法
                if (r.isPersistable()) {
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }

              //將狀態(tài)置為 ON_CREATE
              r.setState(ON_CREATE);
               
        } catch (SuperNotCalledException e) {
            throw e;

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

        return activity;
    }

    public void callActivityOnCreate(Activity activity, Bundle icicle,
            PersistableBundle persistentState) {
        prePerformCreate(activity);
        activity.performCreate(icicle, persistentState);
        postPerformCreate(activity);
    }

    final void performCreate(Bundle icicle, PersistableBundle persistentState) {
        //調用 onCreate 方法
        if (persistentState != null) {
            onCreate(icicle, persistentState);
        } else {
            onCreate(icicle);
        }
      //.....
    }

到這里,activity 的創(chuàng)建和 onCreate 方法的調用就完成了,以此類推 ResumeActivityItem.execute 方法就是調用 activity 的 onResume 方法。那么問題來了,中間的 onStart 方法在什么時候調用呢?還記得下面這一句代碼

    final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
            boolean andResume, boolean checkConfig) throws RemoteException {
          //設置狀態(tài)
          clientTransaction.setLifecycleStateRequest(lifecycleItem);
    }

    //給狀態(tài)賦值
    public void setLifecycleStateRequest(ActivityLifecycleItem stateRequest) {
        mLifecycleStateRequest = stateRequest;
    }

上面的代碼表示將 mLifecycleStateRequest 的值賦為 ResumeActivityItem,還記得之前的一段代碼

    private void executeLifecycleState(ClientTransaction transaction) {
      //獲取最終狀態(tài)的 ActivityLifecycleItem
      //通過上面的賦值可以知道 lifecycleItem 為 ResumeActivityItem
      final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();

        // 循環(huán)到最終請求狀態(tài)
        //lifecycleItem.getTargetState() 值為 ON_RESUME
        cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */);
    }

    public void cycleToPath(ActivityClientRecord r, int finish) {
        cycleToPath(r, finish, false /* excludeLastState */);
    }

    private void cycleToPath(ActivityClientRecord r, int finish,
                             boolean excludeLastState) {
         //獲取當前的狀態(tài)
        //執(zhí)行完 onCreate 方法 所以狀態(tài)為 ON_CREATE
        final int start = r.getLifecycleState();
        //獲取需要執(zhí)行狀態(tài)列表
        final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
        //執(zhí)行
        performLifecycleSequence(r, path);
    }

上面這個方法主要做了三件事:
1.獲取當前生命周期的狀態(tài),通過上面剛執(zhí)行完 onCreate 方法可以知道為 ON_CREATE
2.構建中間需要執(zhí)行的狀態(tài)列表
3.執(zhí)行需要執(zhí)行的狀態(tài)
來看第二件事

    public IntArray getLifecyclePath(int start, int finish, boolean excludeLastState) {
        //....
        //通過分析知道 finish 為 ON_RESUME start 為 ON_CREATE
        //這兩個是一個枚舉類,并且 ON_RESUME > ON_CREATE
        //所以走這個循環(huán)
        if (finish >= start) {  
            // 將中間狀態(tài)增加進去,通過枚舉類可以知道為ON_START
            //所以當前 mLifecycleSequence 中存在的狀態(tài)為 ON_START、 ON_RESUME
            for (int i = start + 1; i <= finish; i++) {
                mLifecycleSequence.add(i);
            }
        } else { 
          //....
        }
        return mLifecycleSequence;
    }

第二件事就是將 ON_START 添加到 mLifecycleSequence 中,繼續(xù)來看第三件事

    private void performLifecycleSequence(ActivityClientRecord r, IntArray path) {
        final int size = path.size();
        for (int i = 0, state; i < size; i++) {
            state = path.get(i);
            log("Transitioning to state: " + state);
            switch (state) {
                case ON_CREATE:
                    mTransactionHandler.handleLaunchActivity(r, mPendingActions,
                            null /* customIntent */);
                    break;
                //通過分析知道,會走這里
                case ON_START:
                     //執(zhí)行 handleStartActivity 就是執(zhí)行 onStart 方法
                    mTransactionHandler.handleStartActivity(r, mPendingActions);
                    break;
                //通過分析,也會走這里
                case ON_RESUME:
                    //調用 handleResumeActivity 就是執(zhí)行 onResume 方法
                    mTransactionHandler.handleResumeActivity(r.token, false /* finalStateRequest */,
                            r.isForward, "LIFECYCLER_RESUME_ACTIVITY");
                    break;
               //..
            }
        }
    }

所以 onStart 方法會在 onResume 之前執(zhí)行,一個問題,這里執(zhí)行了一遍 onResume ,后面又調度執(zhí)行了一遍 onResume,這就是 onResume 可能會執(zhí)行多遍的原因?

到這里,activity 的啟動就到此結束

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容