Android源碼分析-Android9.0下的Activity啓動流程

前言

最近在閱讀Android源碼時,發現最新的Android9.0源碼中startActivity啓動Activity的流程相比於低版本的Android源碼來講改動較大,且本人在網上也沒有找到基於Android9.0的相關源碼分析文章。故寫下此文,記錄下源碼追蹤流程,方便之後本身複查,同時也分享給有須要的讀者。app

Activity->startActivity

@Override
    public void startActivity(Intent intent, @Nullable Bundle options) {
        if (options != null) {
            startActivityForResult(intent, -1, options);
        } else {
            // Note we want to go through this call for compatibility with
            // applications that may have overridden the method.
            startActivityForResult(intent, -1);
        }
    }

直接調用startActivityForResultless

Activity->startActivityForResult

public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
                                       @Nullable Bundle options) {
        // mParent指的是Activity 賦值是在內部API調用setParent方法
        if (mParent == null) {
            options = transferSpringboardActivityOptions(options);
            //Instrumentation爲工具類ActivityResult爲其靜態內部類  工具類調用執行開始Activity方法execStartActity
            //mMainThread爲ActivityThread ,getApplicationThread()方法獲取的是ApplicationThread實例
            //ApplicationThread是ActivityThread的內部類  該類繼承ApplicationThreadNative抽象類,
            //而ApplicationThreadNative繼承Binder類並實現IApplicationThread接口
            //IApplictionThread繼承了IInterface接口
            //Binder類繼承IBinder接口,這就是爲何execStartActivity方法的第二個參數定義爲IBinder
            Instrumentation.ActivityResult ar =
                    mInstrumentation.execStartActivity(
                            this, mMainThread.getApplicationThread(), mToken, this,
                            intent, requestCode, options);
            if (ar != null) {
                // ar不爲空說明Activity啓動成功
                mMainThread.sendActivityResult(
                        mToken, mEmbeddedID, requestCode, ar.getResultCode(),
                        ar.getResultData());
            }
            if (requestCode >= 0) {
                mStartedActivity = true;
            }

            cancelInputsAndStartExitTransition(options);
        } else {
            if (options != null) {
                mParent.startActivityFromChild(this, intent, requestCode, options);
            } else {
                // Note we want to go through this method for compatibility with
                // existing applications that may have overridden it.
                mParent.startActivityFromChild(this, intent, requestCode);
            }
        }
    }

調用了mInstrumentation.execStartActivity方法async

Instrumentation->execStartActivity

public ActivityResult execStartActivity(
        Context who, IBinder contextThread, IBinder token, String target,
        Intent intent, int requestCode, Bundle options) {
        IApplicationThread whoThread = (IApplicationThread) contextThread;
        if (mActivityMonitors != null) {
            synchronized (mSync) {
                final int N = mActivityMonitors.size();
                for (int i=0; i<N; i++) {
                    //ActivityMonitor爲Activity的監測器是Instrumentation的靜態內部類,
                    //當一個Activity啓動時將會被檢測
                    final ActivityMonitor am = mActivityMonitors.get(i);
                    ActivityResult result = null;
                    if (am.ignoreMatchingSpecificIntents()) {
                        result = am.onStartActivity(intent);
                    }
                    if (result != null) {
                        am.mHits++;
                        return result;
                    } else if (am.match(who, null, intent)) {
                        am.mHits++;
                        if (am.isBlocking()) {
                            return requestCode >= 0 ? am.getResult() : null;
                        }
                        break;
                    }
                }
            }
        }
        try {
            intent.migrateExtraStreamToClipData();
            intent.prepareToLeaveProcess(who);
            // result 爲啓動Activity返回的狀態碼
            // 這裏經過IPC機制,調用了ActivityManagerService中的startActivity方法
            int result = ActivityManager.getService()
                .startActivity(whoThread, who.getBasePackageName(), intent,
                        intent.resolveTypeIfNeeded(who.getContentResolver()),
                        token, target, requestCode, 0, null, options);
            //檢查Activity是否啓動成功若未啓動成功則拋出對應異常
            checkStartActivityResult(result, intent);
        } catch (RemoteException e) {
            throw new RuntimeException("Failure from system", e);
        }
        return null;
    }

能夠看到,這個方法最後是調用了ActivityManager.getService().startActivity()方法。
查看ActivityManager源碼ide

ActivityManager->getService

public static IActivityManager getService() {
        return IActivityManagerSingleton.get();
    }

    private static final Singleton<IActivityManager> IActivityManagerSingleton =
            new Singleton<IActivityManager>() {
                @Override
                protected IActivityManager create() {
                    // 經過Binder機制獲取ActivityManagerService
                    final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
                    final IActivityManager am = IActivityManager.Stub.asInterface(b);
                    return am;
                }
            };

這裏是經過Binder的跨進程通訊獲取到了系統服務ActivityManagerService,因此ActivityManager.getService().startActivity()是調用了ActivityManagerService中的startActivity方法。工具

ActivityManagerService->startActivity

@Override
    public final int startActivity(IApplicationThread caller, String callingPackage,
            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
            int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
        return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
                resultWho, requestCode, startFlags, profilerInfo, bOptions,
                UserHandle.getCallingUserId());
    }


    @Override
    public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
            int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
        return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
                resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
                true /*validateIncomingUser*/);
    }

    public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
            int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
            boolean validateIncomingUser) {
        enforceNotIsolatedCaller("startActivity");

        userId = mActivityStartController.checkTargetUser(userId, validateIncomingUser,
                Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");

        // TODO: Switch to user app stacks here.
        // 經過mActivityStartController獲取ActivityStarter,進行後續頁面跳轉
        return mActivityStartController.obtainStarter(intent, "startActivityAsUser")
                .setCaller(caller)
                .setCallingPackage(callingPackage)
                .setResolvedType(resolvedType)
                .setResultTo(resultTo)
                .setResultWho(resultWho)
                .setRequestCode(requestCode)
                .setStartFlags(startFlags)
                .setProfilerInfo(profilerInfo)
                .setActivityOptions(bOptions)
                .setMayWait(userId)
                .execute();
    }

這裏最後經過mActivityStartController.obtainStarter獲取到了一個ActivityStarter對象,而後設置了一些屬性,最後調用了execute()方法。因此流程走到ActivityStarter中的execute()方法。源碼分析

ActivityStarter->execute

int execute() {
        try {
            // TODO(b/64750076): Look into passing request directly to these methods to allow
            // for transactional diffs and preprocessing.
            // ActivityManagerService中的startActivityAsUser方法中調用了setMayWait方法
            // setMayWait方法會將mRequest.mayWait置爲true,因此這裏會走startActivityMayWait方法
            //    ActivityStarter setMayWait(int userId) {
            //        mRequest.mayWait = true;
            //        mRequest.userId = userId;
            //
            //        return this;
            //    }
            if (mRequest.mayWait) {
                return startActivityMayWait(mRequest.caller, mRequest.callingUid,
                        mRequest.callingPackage, mRequest.intent, mRequest.resolvedType,
                        mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
                        mRequest.resultWho, mRequest.requestCode, mRequest.startFlags,
                        mRequest.profilerInfo, mRequest.waitResult, mRequest.globalConfig,
                        mRequest.activityOptions, mRequest.ignoreTargetSecurity, mRequest.userId,
                        mRequest.inTask, mRequest.reason,
                        mRequest.allowPendingRemoteAnimationRegistryLookup);
            } else {
                return startActivity(mRequest.caller, mRequest.intent, mRequest.ephemeralIntent,
                        mRequest.resolvedType, mRequest.activityInfo, mRequest.resolveInfo,
                        mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
                        mRequest.resultWho, mRequest.requestCode, mRequest.callingPid,
                        mRequest.callingUid, mRequest.callingPackage, mRequest.realCallingPid,
                        mRequest.realCallingUid, mRequest.startFlags, mRequest.activityOptions,
                        mRequest.ignoreTargetSecurity, mRequest.componentSpecified,
                        mRequest.outActivity, mRequest.inTask, mRequest.reason,
                        mRequest.allowPendingRemoteAnimationRegistryLookup);
            }
        } finally {
            onExecutionComplete();
        }
    }

查看setMayWait方法post

ActivityStarter setMayWait(int userId) {
        mRequest.mayWait = true;
        mRequest.userId = userId;

        return this;
    }

ActivityManagerService中的startActivityAsUser方法中調用了setMayWait方法。setMayWait方法會將mRequest.mayWait置爲true,因此這裏會走startActivityMayWait方法ui

ActivityStarter->startActivityMayWait

private int startActivityMayWait(IApplicationThread caller, int callingUid,
                                     String callingPackage, Intent intent, String resolvedType,
                                     IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
                                     IBinder resultTo, String resultWho, int requestCode, int startFlags,
                                     ProfilerInfo profilerInfo, WaitResult outResult,
                                     Configuration globalConfig, SafeActivityOptions options, boolean ignoreTargetSecurity,
                                     int userId, TaskRecord inTask, String reason,
                                     boolean allowPendingRemoteAnimationRegistryLookup) {
        
                 ...略

        // Collect information about the target of the Intent.
        // 對Intent參數進行解析獲取Activity的相關信息,並把數據保存在aInfo變量中
        ActivityInfo aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, profilerInfo);
        synchronized (mService) {

                  ...略

            final ActivityRecord[] outRecord = new ActivityRecord[1];
            // 調用ActivityStarter的startActivity方法
            int res = startActivity(caller, intent, ephemeralIntent, resolvedType, aInfo, rInfo,
                    voiceSession, voiceInteractor, resultTo, resultWho, requestCode, callingPid,
                    callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, options,
                    ignoreTargetSecurity, componentSpecified, outRecord, inTask, reason,
                    allowPendingRemoteAnimationRegistryLookup);

                  ....略

            //通知跟蹤器Activity正在啓動
            mSupervisor.getActivityMetricsLogger().notifyActivityLaunched(res, outRecord[0]);
            return res;
        }
    }

調用ActivityStarter的startActivity方法this

ActivityStarter->startActivity

private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
                              String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
                              IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
                              IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
                              String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
                              SafeActivityOptions options,
                              boolean ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[] outActivity,
                              TaskRecord inTask, boolean allowPendingRemoteAnimationRegistryLookup) {
       
        ...一些必要的判斷...

        // 檢查是否有開啓新Activity的權限
        boolean abort = !mSupervisor.checkStartAnyActivityPermission(intent, aInfo, resultWho,
                requestCode, callingPid, callingUid, callingPackage, ignoreTargetSecurity,
                inTask != null, callerApp, resultRecord, resultStack);
        abort |= !mService.mIntentFirewall.checkStartActivity(intent, callingUid,
                callingPid, resolvedType, aInfo.applicationInfo);

         ...

        // 若是咱們開始的活動與當前恢復的活動的UID不一樣,檢查是否容許應用程序切換。
        if (voiceSession == null && (stack.getResumedActivity() == null
                || stack.getResumedActivity().info.applicationInfo.uid != realCallingUid)) {
            if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid,
                    realCallingPid, realCallingUid, "Activity start")) {
                mController.addPendingActivityLaunch(new PendingActivityLaunch(r,
                        sourceRecord, startFlags, stack, callerApp));
                ActivityOptions.abort(checkedOptions);
                return ActivityManager.START_SWITCHES_CANCELED;
            }
        }

        // 加載PendingActivity
        mController.doPendingActivityLaunches(false);

        // 繼續調用方法
        return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
                true /* doResume */, checkedOptions, inTask, outActivity);
    }

繼續調用同名方法startActivitycode

ActivityStarter->startActivity

private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
                              IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
                              int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
                              ActivityRecord[] outActivity) {
        int result = START_CANCELED;
        try {
            mService.mWindowManager.deferSurfaceLayout();
            // 調用startActivityUnchecked方法,返回結果
            result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
                    startFlags, doResume, options, inTask, outActivity);
        } finally {
            // 若是咱們沒法繼續,請解除活動與任務的關聯。使活動處於不完整狀態可能會致使問題,例如在沒有窗口容器的狀況下執行操做。
            final ActivityStack stack = mStartActivity.getStack();
            if (!ActivityManager.isStartResultSuccessful(result) && stack != null) {
                stack.finishActivityLocked(mStartActivity, RESULT_CANCELED,
                        null /* intentResultData */, "startActivity", true /* oomAdj */);
            }
            mService.mWindowManager.continueSurfaceLayout();
        }

        postStartActivityProcessing(r, result, mTargetStack);

        return result;
    }

調用startActivityUnchecked方法

ActivityStarter->startActivityUnchecked

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

        // 初始化ActivityStarter全局變量
        setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession,
                voiceInteractor);

        computeLaunchingTaskFlags();

        computeSourceStack();

        mIntent.setFlags(mLaunchFlags);

        // 判斷是否應將新Activity插入到現有任務棧中
        // 若是不須要,則返回null,若是須要,則返回該任務棧信息
        ActivityRecord reusedActivity = getReusableIntentActivity();

        ......

        // 使新Activity可見
        if (mDoResume) {
            final ActivityRecord topTaskActivity =
                    mStartActivity.getTask().topRunningActivityLocked();
            if (!mTargetStack.isFocusable()
                    || (topTaskActivity != null && topTaskActivity.mTaskOverlay
                    && mStartActivity != topTaskActivity)) {
                mTargetStack.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
                mService.mWindowManager.executeAppTransition();
            } else {
                if (mTargetStack.isFocusable() && !mSupervisor.isFocusedStack(mTargetStack)) {
                    mTargetStack.moveToFront("startActivityUnchecked");
                }
                // 關注這裏
                mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,
                        mOptions);
            }
        } else if (mStartActivity != null) {
            mSupervisor.mRecentTasks.add(mStartActivity.getTask());
        }
        mSupervisor.updateUserStackLocked(mStartActivity.userId, mTargetStack);

        mSupervisor.handleNonResizableTaskIfNeeded(mStartActivity.getTask(), preferredWindowingMode,
                preferredLaunchDisplayId, mTargetStack);

        return START_SUCCESS;
    }

這裏須要關注的是mSupervisor.resumeFocusedStackTopActivityLocked方法

ActivityStackSupervisor->resumeFocusedStackTopActivityLocked

boolean resumeFocusedStackTopActivityLocked(
            ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {

        if (!readyToResume()) {
            return false;
        }

        if (targetStack != null && isFocusedStack(targetStack)) {
            return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
        }

        final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
        if (r == null || !r.isState(RESUMED)) {
            mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
        } else if (r.isState(RESUMED)) {
            // Kick off any lingering app transitions form the MoveTaskToFront operation.
            mFocusedStack.executeAppTransition(targetOptions);
        }

        return false;
    }

能夠看到,這裏調用了resumeTopActivityUncheckedLocked方法

ActivityStackSupervisor->resumeTopActivityUncheckedLocked

boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
        if (mStackSupervisor.inResumeTopActivity) {
            // Don't even start recursing.
            return false;
        }

        boolean result = false;
        try {
            // Protect against recursion.
            mStackSupervisor.inResumeTopActivity = true;
            result = resumeTopActivityInnerLocked(prev, options);

            // When resuming the top activity, it may be necessary to pause the top activity (for
            // example, returning to the lock screen. We suppress the normal pause logic in
            // {@link #resumeTopActivityUncheckedLocked}, since the top activity is resumed at the
            // end. We call the {@link ActivityStackSupervisor#checkReadyForSleepLocked} again here
            // to ensure any necessary pause logic occurs. In the case where the Activity will be
            // shown regardless of the lock screen, the call to
            // {@link ActivityStackSupervisor#checkReadyForSleepLocked} is skipped.
            final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);
            if (next == null || !next.canTurnScreenOn()) {
                checkReadyForSleep();
            }
        } finally {
            mStackSupervisor.inResumeTopActivity = false;
        }

        return result;
    }

這裏調用了resumeTopActivityInnerLocked方法,resumeTopActivityInnerLocked方法中會調用startSpecificActivityLocked方法,而後再調用realStartActivityLocked方法。Activity的啓動事務就是在realStartActivityLocked方法中啓動的。

ActivityStackSupervisor->realStartActivityLocked

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

            ......           

            try {
                
                ......

                // Create activity launch transaction.
                // 建立Activity啓動事務
                // ClientTransaction.obtain方法以下:
                // public static ClientTransaction obtain(IApplicationThread client, IBinder activityToken) {
                //        ClientTransaction instance = ObjectPool.obtain(ClientTransaction.class);
                //        if (instance == null) {
                //            instance = new ClientTransaction();
                //        }
                //        instance.mClient = client;
                //        instance.mActivityToken = activityToken;
                //
                //        return instance;
                // }
                // 這裏傳入的app.thread會賦值給ClientTransaction的成員變量mClient,
                // 而ClientTransaction會調用mClient.scheduleTransaction(this)來執行事務
                // 因此事務最終是調用app.thread的scheduleTransaction執行。
                // 而這個app.thread是ActivityThread的內部類ApplicationThread。
                final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
                        r.appToken);
                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));

                // Set desired final state.
                final ActivityLifecycleItem lifecycleItem;
                if (andResume) {
                    lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
                } else {
                    lifecycleItem = PauseActivityItem.obtain();
                }
                clientTransaction.setLifecycleStateRequest(lifecycleItem);

                // Schedule transaction.
                // 執行Activity啓動事務
                mService.getLifecycleManager().scheduleTransaction(clientTransaction);
              
                ......

            } catch (RemoteException e) {
                if (r.launchFailed) {
                    // 第二次啓動失敗的異常處理
                    return false;
                }

                // 第一次啓動失敗,重試
                r.launchFailed = true;
                app.activities.remove(r);
                throw e;
            }
        } finally {
            endDeferResume();
        }

        ......

        return true;
    }

方法中須要關注的部分已經用註釋說明了,在realStartActivityLocked中最主要的工做就是建立了Activity的啓動事務ClientTransaction,並調用ClientLifecycleManager的scheduleTransaction方法啓動它。接下來,看ClientTransaction事務中是怎麼啓動Activity的。

ClientLifecycleManager->scheduleTransaction

void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
        final IApplicationThread client = transaction.getClient();
        // 執行事務
        transaction.schedule();
        if (!(client instanceof Binder)) {
            // If client is not an instance of Binder - it's a remote call and at this point it is
            // safe to recycle the object. All objects used for local calls will be recycled after
            // the transaction is executed on client in ActivityThread.
            transaction.recycle();
        }
    }

調用ClientTransaction的schedule方法

public void schedule() throws RemoteException {
        mClient.scheduleTransaction(this);
    }

這裏調用了mClient的scheduleTransaction方法,那麼這裏的mClient是從哪來的呢。很容易想到,是在建立ClientTransaction事務對象的時候賦值的,也就是調用obtain方法時。

ClientTransaction->obtain

public static ClientTransaction obtain(IApplicationThread client, IBinder activityToken) {
        ClientTransaction instance = ObjectPool.obtain(ClientTransaction.class);
        if (instance == null) {
            instance = new ClientTransaction();
        }
        instance.mClient = client;
        instance.mActivityToken = activityToken;

        return instance;
    }

咱們回到ActivityStackSupervisor的realStartActivityLocked方法

ActivityStackSupervisor->realStartActivityLocked

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

            ......           

            try {
                
                ......

                // Create activity launch transaction.
                // 建立Activity啓動事務
                // ClientTransaction.obtain方法以下:
                // public static ClientTransaction obtain(IApplicationThread client, IBinder activityToken) {
                //        ClientTransaction instance = ObjectPool.obtain(ClientTransaction.class);
                //        if (instance == null) {
                //            instance = new ClientTransaction();
                //        }
                //        instance.mClient = client;
                //        instance.mActivityToken = activityToken;
                //
                //        return instance;
                // }
                // 這裏傳入的app.thread會賦值給ClientTransaction的成員變量mClient,
                // 而ClientTransaction會調用mClient.scheduleTransaction(this)來執行事務
                // 因此事務最終是調用app.thread的scheduleTransaction執行。
                // 而這個app.thread是ActivityThread的內部類ApplicationThread。
                final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
                        r.appToken);
                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));

                // Set desired final state.
                final ActivityLifecycleItem lifecycleItem;
                if (andResume) {
                    lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
                } else {
                    lifecycleItem = PauseActivityItem.obtain();
                }
                clientTransaction.setLifecycleStateRequest(lifecycleItem);

                // Schedule transaction.
                // 執行Activity啓動事務
                mService.getLifecycleManager().scheduleTransaction(clientTransaction);
              
                ......

            } catch (RemoteException e) {
                if (r.launchFailed) {
                    // 第二次啓動失敗的異常處理
                    return false;
                }

                // 第一次啓動失敗,重試
                r.launchFailed = true;
                app.activities.remove(r);
                throw e;
            }
        } finally {
            endDeferResume();
        }

        ......

        return true;
    }

能夠看到,賦值給mClient的是app.thread,因此事務最終是調用的app.thread的scheduleTransaction方法來執行,而這個app.thread是ActivityThread的內部類ApplicationThread。因此流程轉到了ActivityThread的內部類ApplicationThread中。

ActivityThread->ApplicationThread->scheduleTransaction

@Override
    public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
        ActivityThread.this.scheduleTransaction(transaction);
    }

這裏仍是調用了ActivityThread的scheduleTransaction方法。可是在查看ActivityThread類就會發現ActivityThread類中並無scheduleTransaction這個方法。所以天然會想到極可能是繼承的父類中的方法。ActivityThread繼承的是ClientTransactionHandler類。到ClientTransactionHandler類中一查,果真發現了scheduleTransaction方法。因此這裏最終調用的就是ClientTransactionHandler中的scheduleTransaction方法。

ClientTransactionHandler->scheduleTransaction

void scheduleTransaction(ClientTransaction transaction) {
        transaction.preExecute(this);
        sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
    }

這裏調用了sendMessage方法,而sendMessage是一個抽象方法,因此這裏調用的是ActivityThread類中的sendMessage實現。

ActivityThread->sendMessage

private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
        if (DEBUG_MESSAGES) Slog.v(
            TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
            + ": " + arg1 + " / " + obj);
        Message msg = Message.obtain();
        msg.what = what;
        msg.obj = obj;
        msg.arg1 = arg1;
        msg.arg2 = arg2;
        if (async) {
            msg.setAsynchronous(true);
        }
        mH.sendMessage(msg);
    }

這裏就是生成了一個Message對象,並向mH這個Handler發送該消息。因此這裏mH將會接受到一個what爲ActivityThread.H.EXECUTE_TRANSACTION的消息。去查看Handler中對EXECUTE_TRANSACTION消息的處理。

ActivityThread->H->handleMessage

case EXECUTE_TRANSACTION:
        final ClientTransaction transaction = (ClientTransaction) msg.obj;
        // 調用TransactionExecutor的execute方法
        mTransactionExecutor.execute(transaction);
        if (isSystem()) {
            // Client transactions inside system process are recycled on the client side
            // instead of ClientLifecycleManager to avoid being cleared before this
            // message is handled.
            transaction.recycle();
        }
        // TODO(lifecycler): Recycle locally scheduled transactions.
        break;

這裏調用了TransactionExecutor的execute方法

TransactionExecutor->execute

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

        executeCallbacks(transaction);

        executeLifecycleState(transaction);
        mPendingActions.clear();
        log("End resolving transaction");
    }

這裏調用了executeCallbacks和executeLifecycleState兩個方法,查看兩個方法就會發現,這兩個方法最後都會調用cycleToPath這個方法。

TransactionExecutor->cycleToPath

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);
    }

TransactionExecutor->performLifecycleSequence

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:
                    mTransactionHandler.handleStartActivity(r, mPendingActions);
                    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);
            }
        }
    }

看到這裏就豁然開朗了,Activity的生命週期就是在這裏進行一個相關方法的調用。
這裏的成員變量mTransactionHandler是一個ClientTransactionHandler對象,在ClientTransactionHandler中這些方法都是抽象方法,這裏執行的是ClientTransactionHandler的實現類ActivityThread中的handleLaunchActivity方法。

ActivityThread->handleLaunchActivity

public Activity handleLaunchActivity(ActivityClientRecord r,
            PendingTransactionActions pendingActions, Intent customIntent) {
        // If we are getting ready to gc after going to the background, well
        // we are back active so skip it.
        unscheduleGcIdler();
        mSomeActivitiesChanged = true;

        if (r.profilerInfo != null) {
            mProfiler.setProfiler(r.profilerInfo);
            mProfiler.startProfiling();
        }

        // Make sure we are running with the most recent config.
        handleConfigurationChanged(null, null);

        if (localLOGV) Slog.v(
            TAG, "Handling launch of " + r);

        // Initialize before creating the activity
        if (!ThreadedRenderer.sRendererDisabled) {
            GraphicsEnvironment.earlyInitEGL();
        }
        //建立WindowManagerServer
        WindowManagerGlobal.initialize();

        // 經過反射建立指定的Activity,並回調Activity的performCreate方法執行onCreate
        final Activity a = performLaunchActivity(r, customIntent);

        if (a != null) {
            r.createdConfig = new Configuration(mConfiguration);
            reportSizeConfigurations(r);
            if (!r.activity.mFinished && pendingActions != null) {
                pendingActions.setOldState(r.state);
                pendingActions.setRestoreInstanceState(true);
                pendingActions.setCallOnPostCreate(true);
            }
        } else {
            // If there was an error, for any reason, tell the activity manager to stop us.
            try {
                ActivityManager.getService()
                        .finishActivity(r.token, Activity.RESULT_CANCELED, null,
                                Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
            } catch (RemoteException ex) {
                throw ex.rethrowFromSystemServer();
            }
        }

        return a;
    }

到這,Activity的啓動流程也就走完了。

能夠看到,一個startActivity方法在源碼中的處理是多麼的複雜。若是咱們不去閱讀源碼的話,根本不會對Activity的啓動有一個更深層的理解。因此做爲開發,保持一個閱讀源碼的習慣是很是重要的。

但願本文能對各位讀者有一點幫助,也歡迎指出文章中的錯誤,謝謝你們。

相關文章
相關標籤/搜索