基于Android 9.0的Activity啟動(dòng)流程源碼分析

9.0剛剛發(fā)布沒(méi)多久轴猎,就趕緊下載了源碼看了一下,發(fā)現(xiàn)Activity的啟動(dòng)流程有點(diǎn)小改動(dòng)秃殉,但是總體上還是和以前差不多免绿。在閱讀過(guò)程中可以參照如下流程圖:

Activity啟動(dòng)流程圖.png

如果圖片看不清楚可以訪問(wèn)此鏈接:http://img0.ph.126.net/0BLQn4KbOlpQC9xT2ou33Q==/6597964769123998566.png

首先從startActivity這個(gè)方法入手凡伊,如下代碼所示:

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

和之前的一樣零渐,其實(shí)都是調(diào)用了 startActivityForResult 方法,這里有兩個(gè)重載的 startActivityForResult 方法系忙,我們可以進(jìn)去注釋2的方法中看诵盼,繼續(xù)點(diǎn)進(jìn)去:

    public void startActivityForResult(@RequiresPermission Intent intent, int requestCode) {
        startActivityForResult(intent, requestCode, null);
    }

好吧,其實(shí)執(zhí)行的還是注釋1的方法银还,只是Bundle類(lèi)型的options設(shè)置為null來(lái)間接調(diào)用了而已风宁,其實(shí)平常編碼過(guò)程中,像這種如果多個(gè)方法本質(zhì)功能其實(shí)一樣的蛹疯,但是對(duì)于具體的執(zhí)行流程不一樣的可以通過(guò)不同的參數(shù)來(lái)控制邏輯戒财,盡量達(dá)到復(fù)用的效果,邏輯也清晰捺弦。接下來(lái)繼續(xù)點(diǎn)進(jìn)去繼續(xù)查看:

    public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
            @Nullable Bundle options) {
        if (mParent == null) {
            options = transferSpringboardActivityOptions(options);
            Instrumentation.ActivityResult ar =
                mInstrumentation.execStartActivity(
                    this, mMainThread.getApplicationThread(), mToken, this,
                    intent, requestCode, options);      //注釋1:?jiǎn)?dòng)Activity
            if (ar != null) {
                mMainThread.sendActivityResult(
                    mToken, mEmbeddedID, requestCode, ar.getResultCode(),
                    ar.getResultData());
            }
            if (requestCode >= 0) {
                // If this start is requesting a result, we can avoid making
                // the activity visible until the result is received.  Setting
                // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
                // activity hidden during this time, to avoid flickering.
                // This can only be done when a result is requested because
                // that guarantees we will get information back when the
                // activity is finished, no matter what happens to it.
                mStartedActivity = true;
            }

            cancelInputsAndStartExitTransition(options);
            // TODO Consider clearing/flushing other event sources and events for child windows.
        } 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);
            }
        }
    }

無(wú)論怎么樣饮寞,最后都會(huì)執(zhí)行這個(gè)方法的。很多人都會(huì)問(wèn)這個(gè)mParent是什么東東來(lái)的列吼,我們可以直接點(diǎn)擊一下:

    /*package*/ ActivityInfo mActivityInfo;
    /*package*/ ActivityThread mMainThread;
    Activity mParent;
    boolean mCalled;
    /*package*/ boolean mResumed;
    /*package*/ boolean mStopped;

原來(lái)是Activity類(lèi)型來(lái)的幽崩。由于我們的Activity還沒(méi)啟動(dòng),所以mParent為null寞钥,所以判斷條件成立慌申,執(zhí)行了注釋1的代碼:

         Instrumentation.ActivityResult ar =
                mInstrumentation.execStartActivity(
                    this, mMainThread.getApplicationThread(), mToken, this,
                    intent, requestCode, options);

在這里執(zhí)行了Instrumentation類(lèi)的execStartActivity方法,并且返回了ActivityResult理郑,ActivityResult是Instrumentation的一個(gè)內(nèi)部類(lèi)蹄溉,代表著Activity的啟動(dòng)結(jié)果數(shù)據(jù)咨油,而Instrumentation的作用則是監(jiān)控整個(gè)APP運(yùn)行流程、交互流程类缤。很多時(shí)候臼勉,要多看注釋?zhuān)瑒倓傞_(kāi)始我也不知道這個(gè)類(lèi)是干什么的,為什么還要多寫(xiě)這一層餐弱,知道我看到這些類(lèi)的注釋說(shuō)明:
Instrumentation :

/**
 * Base class for implementing application instrumentation code.  When running
 * with instrumentation turned on, this class will be instantiated for you
 * before any of the application code, allowing you to monitor all of the
 * interaction the system has with the application.  An Instrumentation
 * implementation is described to the system through an AndroidManifest.xml's
 * <instrumentation> tag.
 */

public class Instrumentation  {

ActivityResult :

    /**
     * Description of a Activity execution result to return to the original
     * activity.
     */
    public static final class ActivityResult {

接下來(lái)繼續(xù)看注釋1中執(zhí)行的方法:

public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {
        IApplicationThread whoThread = (IApplicationThread) contextThread;
        Uri referrer = target != null ? target.onProvideReferrer() : null;
        if (referrer != null) {
            intent.putExtra(Intent.EXTRA_REFERRER, referrer);
        }
        if (mActivityMonitors != null) {
            synchronized (mSync) {
                final int N = mActivityMonitors.size();
                for (int i=0; i<N; i++) {
                    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);
            int result = ActivityManager.getService()                    
                .startActivity(whoThread, who.getBasePackageName(), intent,
                        intent.resolveTypeIfNeeded(who.getContentResolver()),
                        token, target != null ? target.mEmbeddedID : null,
                        requestCode, 0, null, options);      //注釋1
            checkStartActivityResult(result, intent);    //注釋2
        } catch (RemoteException e) {
            throw new RuntimeException("Failure from system", e);
        }
        return null;
    }

注釋1中獲取了ActivityManager的服務(wù)(AMS)來(lái)啟動(dòng)Activity宴霸,注釋2則是對(duì)啟動(dòng)結(jié)果進(jìn)行檢查,先看 checkStartActivityResult 方法:

    public static void checkStartActivityResult(int res, Object intent) {
        if (!ActivityManager.isStartResultFatalError(res)) {
            return;
        }

        switch (res) {
            case ActivityManager.START_INTENT_NOT_RESOLVED:
            case ActivityManager.START_CLASS_NOT_FOUND:
                if (intent instanceof Intent && ((Intent)intent).getComponent() != null)
                    throw new ActivityNotFoundException(
                            "Unable to find explicit activity class "
                            + ((Intent)intent).getComponent().toShortString()
                            + "; have you declared this activity in your AndroidManifest.xml?");
                throw new ActivityNotFoundException(
                        "No Activity found to handle " + intent);
            case ActivityManager.START_PERMISSION_DENIED:
                throw new SecurityException("Not allowed to start activity "
                        + intent);
            case ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT:
                throw new AndroidRuntimeException(
                        "FORWARD_RESULT_FLAG used while also requesting a result");
            case ActivityManager.START_NOT_ACTIVITY:
                throw new IllegalArgumentException(
                        "PendingIntent is not an activity");
            case ActivityManager.START_NOT_VOICE_COMPATIBLE:
                throw new SecurityException(
                        "Starting under voice control not allowed for: " + intent);
            case ActivityManager.START_VOICE_NOT_ACTIVE_SESSION:
                throw new IllegalStateException(
                        "Session calling startVoiceActivity does not match active session");
            case ActivityManager.START_VOICE_HIDDEN_SESSION:
                throw new IllegalStateException(
                        "Cannot start voice activity on a hidden session");
            case ActivityManager.START_ASSISTANT_NOT_ACTIVE_SESSION:
                throw new IllegalStateException(
                        "Session calling startAssistantActivity does not match active session");
            case ActivityManager.START_ASSISTANT_HIDDEN_SESSION:
                throw new IllegalStateException(
                        "Cannot start assistant activity on a hidden session");
            case ActivityManager.START_CANCELED:
                throw new AndroidRuntimeException("Activity could not be started for "
                        + intent);
            default:
                throw new AndroidRuntimeException("Unknown error code "
                        + res + " when starting " + intent);
        }
    }

看到這里是否有點(diǎn)熟悉這里拋出的異常膏蚓,特別是沒(méi)有在AndroidManifest注冊(cè)的Activity的異常F靶弧!驮瞧!這里會(huì)對(duì)啟動(dòng)Activity的結(jié)果返回做一個(gè)檢查判斷氓扛,所以叫 checkStartActivityResult ,看來(lái)命名真的很重要论笔,一個(gè)好的命名對(duì)于代碼的職能和邏輯會(huì)有一個(gè)直接的反映采郎。
好了,我們可以返回繼續(xù)看注釋1的方法狂魔。
ActivityManager.getService() 看著字面的意思就是獲取AMS,我們可以直接點(diǎn)getService()方法來(lái)看對(duì)象到底是不是蒜埋。

    /**
     * @hide
     */
    public static IActivityManager getService() {
        return IActivityManagerSingleton.get();   //注釋1
    }

    private static final Singleton<IActivityManager> IActivityManagerSingleton =
            new Singleton<IActivityManager>() {
                @Override
                protected IActivityManager create() {
                    final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);   //注釋2
                    final IActivityManager am = IActivityManager.Stub.asInterface(b); //注釋3
                    return am;
                }
            };

在注釋1中通過(guò)IActivityManagerSingleton的get()直接返回了IActivityManager 對(duì)象,繼續(xù)往下看get()方法最楷。在注釋2獲取了ACTIVITY_SERVICE的服務(wù)整份,即Activity有關(guān)的服務(wù),是系統(tǒng)級(jí)別的服務(wù)籽孙,返回了一個(gè)IBinder的對(duì)象烈评,這有又是一個(gè)進(jìn)程間的通信方式。然后在注釋3中通過(guò)AIDL生成了IActivityManager并且返回犯建。所以我們可以知道IActivityManager通過(guò)IBinder的AIDL方式來(lái)獲取到對(duì)象的讲冠,但是這只是一個(gè)接口,我們需要找到的是實(shí)現(xiàn)類(lèi)适瓦,即 ActivityManagerService 竿开。


public class ActivityManagerService extends IActivityManager.Stub
        implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {

    /**
     * Priority we boost main thread and RT of top app to.
     */
    public static final int TOP_APP_PRIORITY_BOOST = -10;

    private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityManagerService" : TAG_AM;
    private static final String TAG_BACKUP = TAG + POSTFIX_BACKUP;

從ActivityManagerService的聲明中可以看到該類(lèi)繼承了IActivityManager.Stub,剛剛好是AIDL方式犹菇。我們?cè)谠擃?lèi)中可以直接搜索 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());   //注釋1
    }

    @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*/);   //注釋2
    }

    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) {
         //確定進(jìn)程是否被隔離了 隔離了就直接拋異常
        enforceNotIsolatedCaller("startActivity");   //注釋3

         //檢查啟動(dòng)Activity的userId是否是合法的
        userId = mActivityStartController.checkTargetUser(userId, validateIncomingUser,
                Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");    //注釋4
          
        // TODO: Switch to user app stacks here.
        return mActivityStartController.obtainStarter(intent, "startActivityAsUser")   //注釋5
                .setCaller(caller)
                .setCallingPackage(callingPackage)
                .setResolvedType(resolvedType)
                .setResultTo(resultTo)
                .setResultWho(resultWho)
                .setRequestCode(requestCode)
                .setStartFlags(startFlags)
                .setProfilerInfo(profilerInfo)
                .setActivityOptions(bOptions)
                .setMayWait(userId)
                .execute();     

    }

隨著一路的調(diào)用德迹,直到注釋5的方法。
mActivityStartController到底是什么揭芍?可以直接點(diǎn)擊:

/**
 * Controller for delegating activity launches.
 *
 * This class' main objective is to take external activity start requests and prepare them into
 * a series of discrete activity launches that can be handled by an {@link ActivityStarter}. It is
 * also responsible for handling logic that happens around an activity launch, but doesn't
 * necessarily influence the activity start. Examples include power hint management, processing
 * through the pending activity list, and recording home activity launches.
 */
public class ActivityStartController {
    private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityStartController" : TAG_AM;

    private static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 1;

    private final ActivityManagerService mService;
    private final ActivityStackSupervisor mSupervisor;

大意就是:以委托的方式處理啟動(dòng)Activity胳搞,算是一個(gè)中間類(lèi),對(duì)ActivityStarter類(lèi)進(jìn)行處理,可以不影響啟動(dòng)結(jié)果肌毅,只負(fù)責(zé)間接傳遞處理筷转。說(shuō)白了就是一個(gè)間接類(lèi),在ActivityStarter和ActivityManagerService加多一層而已悬而。
接下來(lái)直接點(diǎn)擊obtainStarter方法呜舒,看一下到底是哪個(gè)類(lèi)來(lái)執(zhí)行。

 ActivityStarter obtainStarter(Intent intent, String reason) {
        return mFactory.obtain().setIntent(intent).setReason(reason);
    }

可以看到最后是交由ActivityStarter類(lèi)來(lái)執(zhí)行笨奠。ActivityStarter 是專(zhuān)門(mén)把intent袭蝗、flag轉(zhuǎn)變?yōu)锳ctivity,同時(shí)把Activity的任務(wù)棧關(guān)聯(lián)起來(lái)般婆,源碼如是注釋到:

/**
 * Controller for interpreting how and then launching an activity.
 *
 * This class collects all the logic for determining how an intent and flags should be turned into
 * an activity and associated task and stack.
 */
class ActivityStarter {

我們看execute()方法:

    /**
     * Starts an activity based on the request parameters provided earlier.
     * @return The starter result.
     */
    int execute() {
        try {
            // TODO(b/64750076): Look into passing request directly to these methods to allow
            // for transactional diffs and preprocessing.
            if (mRequest.mayWait) {   
                return startActivityMayWait(mRequest.caller, mRequest.callingUid,    //注釋1
                        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,     //注釋2
                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();
        }
    }

通過(guò)上個(gè)方法鏈路調(diào)用用了setMayWait(userId)的方法可以知道m(xù)Request.mayWait = true 如下面代碼所示:

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

        return this;
    }

所以判斷條件成立到腥,執(zhí)行注釋1的方法,由于 startActivityMayWait 方法篇幅過(guò)長(zhǎng)蔚袍,這里我只貼關(guān)鍵的幾步:

  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) {

     mSupervisor.getActivityMetricsLogger().notifyActivityLaunching();
        boolean componentSpecified = intent.getComponent() != null;

        final int realCallingPid = Binder.getCallingPid();
        final int realCallingUid = Binder.getCallingUid();
        ......
        ......
        ......
       //解析Intent的數(shù)據(jù)
           ResolveInfo rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId,
                0 /* matchFlags */,
                        computeResolveFilterUid(
                                callingUid, realCallingUid, mRequest.filterCallingUid));
        ......
        // Collect information about the target of the Intent.
        ActivityInfo aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, profilerInfo);
        ......
        //用于記錄Activity的數(shù)據(jù)
         final ActivityRecord[] outRecord = new ActivityRecord[1];
           //注釋1 啟動(dòng)Activity
            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);

點(diǎn)擊注釋1的 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, String reason,
            boolean allowPendingRemoteAnimationRegistryLookup) {

        if (TextUtils.isEmpty(reason)) {
            throw new IllegalArgumentException("Need to specify a reason.");
        }
        mLastStartReason = reason;
        mLastStartActivityTimeMs = System.currentTimeMillis();
        mLastStartActivityRecord[0] = null;
        //注釋1 啟動(dòng)Activuty
        mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,
                aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
                callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
                options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,
                inTask, allowPendingRemoteAnimationRegistryLookup);

        if (outActivity != null) {
            // mLastStartActivityRecord[0] is set in the call to startActivity above.
            outActivity[0] = mLastStartActivityRecord[0];
        }

        return getExternalResult(mLastStartActivityResult);
    }

再次點(diǎn)擊注釋1的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) {
        int err = ActivityManager.START_SUCCESS;
        // Pull the optional Ephemeral Installer-only bundle out of the options early.
        final Bundle verificationBundle
                = options != null ? options.popAppVerificationBundle() : null;

        ProcessRecord callerApp = null;
        ......
       //檢查啟動(dòng)Activityd的權(quán)限
        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);
        ......
            if (mService.mDidAppSwitch) {
            // This is the second allowed switch since we stopped switches,
            // so now just generally allow switches.  Use case: user presses
            // home (switches disabled, switch to home, mDidAppSwitch now true);
            // user taps a home icon (coming from home so allowed, we hit here
            // and now allow anyone to switch again).
            mService.mAppSwitchesAllowedTime = 0;
        } else {
            mService.mDidAppSwitch = true;
        }

        mController.doPendingActivityLaunches(false);

        return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
                true /* doResume */, checkedOptions, inTask, outActivity);   //注釋1

在最后返回的時(shí)候執(zhí)行了startActivity 方法乡范,直接點(diǎn)擊:

    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();
             //注釋1
            result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
                    startFlags, doResume, options, inTask, outActivity);
        } finally {
            // If we are not able to proceed, disassociate the activity from the task. Leaving an
            // activity in an incomplete state can lead to issues, such as performing operations
            // without a window container.

            //獲取Activity的任務(wù)棧
            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;
    }

繼續(xù)點(diǎn)擊注釋1的startActivityUnchecked 方法:

    // Note: This method should only be called from {@link startActivity}.
    private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
            ActivityRecord[] outActivity) {

        setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession,
                voiceInteractor);

        computeLaunchingTaskFlags();      //處理Activity的啟動(dòng)模式,確定Activity的啟動(dòng)模式

        computeSourceStack();   
  
            //根據(jù)Activity啟動(dòng)模式來(lái)設(shè)置棧
            if (mStartActivity.getTask() == null && !clearTopAndResetStandardLaunchMode) {
                mStartActivity.setTask(reusedActivity.getTask());
            }

            if (reusedActivity.getTask().intent == null) {
                // This task was started because of movement of the activity based on affinity...
                // Now that we are actually launching it, we can assign the base intent.
                reusedActivity.getTask().setIntent(mStartActivity);
            }
       ......
         reusedActivity = setTargetStackAndMoveToFrontIfNeeded(reusedActivity);    //注釋2
......
         mTargetStack.startActivityLocked(mStartActivity, topFocused, newTask, mKeepCurTransition,
                mOptions);     //根據(jù)Activity的啟動(dòng)模式來(lái)判斷是直接插入已存在的棧頂還是新開(kāi)棧插入

        if (mDoResume) {    // mDoResume = true;
            final ActivityRecord topTaskActivity =
                    mStartActivity.getTask().topRunningActivityLocked();
            if (!mTargetStack.isFocusable()
                    || (topTaskActivity != null && topTaskActivity.mTaskOverlay
                    && mStartActivity != topTaskActivity)) {
                // If the activity is not focusable, we can't resume it, but still would like to
                // make sure it becomes visible as it starts (this will also trigger entry
                // animation). An example of this are PIP activities.
                // Also, we don't want to resume activities in a task that currently has an overlay
                // as the starting activity just needs to be in the visible paused state until the
                // over is removed.
                mTargetStack.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
                // Go ahead and tell window manager to execute app transition for this activity
                // since the app transition will not be triggered through the resume channel.
                mService.mWindowManager.executeAppTransition();
            } else {
                // If the target stack was not previously focusable (previous top running activity
                // on that stack was not visible) then any prior calls to move the stack to the
                // will not update the focused stack.  If starting the new activity now allows the
                // task stack to be focusable, then ensure that we now update the focused stack
                // accordingly.
                if (mTargetStack.isFocusable() && !mSupervisor.isFocusedStack(mTargetStack)) {
                    mTargetStack.moveToFront("startActivityUnchecked");
                }
                mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,
                        mOptions);          //注釋1
            }
        } else if (mStartActivity != null) {
            mSupervisor.mRecentTasks.add(mStartActivity.getTask());
        }

經(jīng)過(guò)一系列的邏輯處理之后啤咽,在注釋1中晋辆,調(diào)用了ActivityStackSupervisor的 resumeFocusedStackTopActivityLocked 方法,繼續(xù)點(diǎn)進(jìn)去:

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

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

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

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

根據(jù)傳過(guò)來(lái)的參數(shù)可知宇整,targetStack不為null瓶佳,而且isFocusedStack(targetStack)判斷也為true,所以判斷條件為true没陡,進(jìn)入執(zhí)行resumeTopActivityUncheckedLocked方法涩哟,ActivityStack 是負(fù)責(zé)管理將要啟動(dòng)的Activity所處于的任務(wù)棧,繼續(xù)進(jìn)入到 ActivityStack 類(lèi)中的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);    //注釋1

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

繼續(xù)看注釋1的代碼:

    private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
        if (!mService.mBooting && !mService.mBooted) {
            // Not ready yet!
            return false;
        }

        // Find the next top-most activity to resume in this stack that is not finishing and is
        // focusable. If it is not focusable, we will fall into the case below to resume the
        // top activity in the next focusable task.
        final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);

          ......

         mStackSupervisor.startSpecificActivityLocked(next, true, false);     //注釋1

          ......

注釋1中再次調(diào)用了 ActivityStackSupervisor 的方法索赏,回調(diào)過(guò)程重新交給了 ActivityStackSupervisor 繼續(xù)點(diǎn)進(jìn)去看startSpecificActivityLocked:

    void startSpecificActivityLocked(ActivityRecord r,
            boolean andResume, boolean checkConfig) {
        // Is this activity's application already running?
        ProcessRecord app = mService.getProcessRecordLocked(r.processName,
                r.info.applicationInfo.uid, true);

        getLaunchTimeTracker().setLaunchTime(r);

        if (app != null && app.thread != null) {
            try {
                if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
                        || !"android".equals(r.info.packageName)) {
                    // Don't add this if it is a platform component that is marked
                    // to run in multiple processes, because this is actually
                    // part of the framework so doesn't make sense to track as a
                    // separate apk in the process.
                    app.addPackage(r.info.packageName, r.info.applicationInfo.longVersionCode,
                            mService.mProcessStats);
                }
                realStartActivityLocked(r, app, andResume, checkConfig);    //注釋1
                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.
        }

        mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
                "activity", r.intent.getComponent(), false, false, true);
    }

繼續(xù)點(diǎn)進(jìn)去查看上面代碼注釋1所執(zhí)行的 realStartActivityLocked 方法:

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

        if (!allPausedActivitiesComplete()) {
            // While there are activities pausing we skipping starting any new activities until
            // pauses are complete. NOTE: that we also do this for activities that are starting in
            // the paused state because they will first be resumed then paused on the client side.
            if (DEBUG_SWITCH || DEBUG_PAUSE || DEBUG_STATES) Slog.v(TAG_PAUSE,
                    "realStartActivityLocked: Skipping start of r=" + r
                    + " some activities pausing...");
            return false;
        }

         ......
             //注釋2
             // Create activity launch transaction.   
                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.
                mService.getLifecycleManager().scheduleTransaction(clientTransaction);
          ......

9.0相對(duì)于其他低版本的版本盼玄,改動(dòng)最大的就是注釋2的代碼塊了,我們先貼 8.0的代碼:

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

       if (!allPausedActivitiesComplete()) {
           // While there are activities pausing we skipping starting any new activities until
           // pauses are complete. NOTE: that we also do this for activities that are starting in
           // the paused state because they will first be resumed then paused on the client side.
           if (DEBUG_SWITCH || DEBUG_PAUSE || DEBUG_STATES) Slog.v(TAG_PAUSE,
                   "realStartActivityLocked: Skipping start of r=" + r
                   + " some activities pausing...");
            return false;
        }

       ......

        app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
                   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, !andResume,
                    mService.isNextTransitionForward(), profilerInfo);

        ......

通過(guò)對(duì)比9.0和8.0的代碼比較潜腻,可以發(fā)現(xiàn)9.0是通過(guò)事務(wù)機(jī)制來(lái)啟動(dòng)Activity埃儿,而8.0則是直接通過(guò)主線(xiàn)程:app.thread.scheduleLaunchActivity 調(diào)度來(lái)執(zhí)行的,這是最大的一個(gè)差別融涣,我們先看9.0的代碼先童番。9.0中,通過(guò)ClientTransaction來(lái)管理了Activity的啟動(dòng)過(guò)程威鹿,該類(lèi)包含了客戶(hù)端(app)的一系列的消息剃斧,可以對(duì)這些消息做出反應(yīng)回調(diào),并且發(fā)送給客戶(hù)端忽你,讓客戶(hù)端也就是app去執(zhí)行回調(diào),完成具體的消息執(zhí)行和整個(gè)生命周期的調(diào)度執(zhí)行幼东。接著,先看 scheduleTransaction 方法執(zhí)行,是ClientLifecycleManager 的一個(gè)方法:

    void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
        final IApplicationThread client = transaction.getClient();
        transaction.schedule();   //注釋1
        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();
        }
    }

由于client本來(lái)就是Binder根蟹,所以不用考慮判斷脓杉,直接看注釋1:

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

通過(guò)mClient = 直接類(lèi)內(nèi)搜索可以看一下是什么類(lèi)型:

    /** Target client. */
    private IApplicationThread mClient;
    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;
    }

可以看到 mClient 是IApplicationThread類(lèi)型的,并且在執(zhí)行 obtain 方法的時(shí)候賦值了简逮。還記得 ActivityStackSupervisor 在執(zhí)行realStartActivityLocked 方法的時(shí)候注釋2執(zhí)行了 obtain 方法球散,可以看到第一個(gè)參數(shù)傳的是 app.thread 也就是IApplicationThread類(lèi)型,是ActivityThread的一個(gè)內(nèi)部類(lèi):ApplicationThread散庶,在這之前已經(jīng)賦值了〗堆撸現(xiàn)在看ApplicationThread的 scheduleTransaction :方法:

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

可以看出執(zhí)行的還是ActivityThread的scheduleTransaction方法,但是由于ActivityThread繼承與ClientTransactionHandler悲龟,而且沒(méi)有重寫(xiě)scheduleTransaction方法嘁灯,所以我們直接看ClientTransactionHandler的scheduleTransaction方法,記住對(duì)象還是ActivityThread的:

    void scheduleTransaction(ClientTransaction transaction) {
        transaction.preExecute(this);   //在啟動(dòng)前執(zhí)行
        sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
    }

通過(guò)sendMessage給ActivityThread的H發(fā)送消息躲舌,而H繼承與Handler丑婿,我們可以直接點(diǎn)進(jìn)去看看在H中對(duì)EXECUTE_TRANSACTION是如何做處理的:

  class H extends Handler {

    ......
 public void handleMessage(Message msg) {

    ......
         case EXECUTE_TRANSACTION:
                    final ClientTransaction transaction = (ClientTransaction) msg.obj;
                    mTransactionExecutor.execute(transaction);   //注釋1
                    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;
    ......
}
    ......
}

直接看注釋1,接下來(lái)流程轉(zhuǎn)到了TransactionExecutor處理:

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

        executeCallbacks(transaction);    //注釋1

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

點(diǎn)擊注釋1:

    public void executeCallbacks(ClientTransaction transaction) {
        final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
        if (callbacks == null) {
            // No callbacks to execute, return early.
            return;
        }
        log("Resolving callbacks");

        //從服務(wù)中獲取客戶(hù)端APP(自己正在使用的APP)
        final IBinder token = transaction.getActivityToken();
        ActivityClientRecord r = mTransactionHandler.getActivityClient(token);

        // In case when post-execution state of the last callback matches the final state requested
        // for the activity in this transaction, we won't do the last transition here and do it when
        // moving to final state instead (because it may contain additional parameters from server).
        final ActivityLifecycleItem finalStateRequest = transaction.getLifecycleStateRequest();
        final int finalState = finalStateRequest != null ? finalStateRequest.getTargetState()
                : UNDEFINED;
        // Index of the last callback that requests some post-execution state.
        final int lastCallbackRequestingState = lastCallbackRequestingState(transaction);

        final int size = callbacks.size();
        for (int i = 0; i < size; ++i) {
            final ClientTransactionItem item = callbacks.get(i);
            log("Resolving callback: " + item);
            final int postExecutionState = item.getPostExecutionState();
            final int closestPreExecutionState = mHelper.getClosestPreExecutionState(r,
                    item.getPostExecutionState());
            if (closestPreExecutionState != UNDEFINED) {
                cycleToPath(r, closestPreExecutionState);
            }

            // 注釋2 執(zhí)行啟動(dòng)Activity 
            item.execute(mTransactionHandler, token, mPendingActions);
            item.postExecute(mTransactionHandler, token, mPendingActions);
            if (r == null) {
                // Launch activity request will create an activity record.
                r = mTransactionHandler.getActivityClient(token);
            }

            if (postExecutionState != UNDEFINED && r != null) {
                // Skip the very last transition and perform it by explicit state request instead.
                final boolean shouldExcludeLastTransition =
                        i == lastCallbackRequestingState && finalState == postExecutionState;
                cycleToPath(r, postExecutionState, shouldExcludeLastTransition);
            }
        }
    }

可以看到通過(guò) item.execute(mTransactionHandler, token, mPendingActions) 來(lái)執(zhí)行啟動(dòng)Activity没卸,而item也就是ClientTransactionItem 到底是什么羹奉?從源碼中的類(lèi)聲明可以知道ClientTransactionItem 是作為系統(tǒng)與客戶(hù)端(APP)的回調(diào)樞紐,比如配置變化约计、多窗口模式改變诀拭、Activity的啟動(dòng)等等

/**
 * A callback message to a client that can be scheduled and executed.
 * Examples of these might be activity configuration change, multi-window mode change, activity
 * result delivery etc.
 *
 * @see ClientTransaction
 * @see com.android.server.am.ClientLifecycleManager
 * @hide
 */
public abstract class ClientTransactionItem implements BaseClientRequest, Parcelable {
      ......
}

由于我們看到的只是一個(gè)抽象類(lèi),我們需要找到其實(shí)現(xiàn)類(lèi)才可以煤蚌。還記得在分析ActivityStackSupervisor 的 realStartActivityLocked方法的時(shí)候:

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

        if (!allPausedActivitiesComplete()) {
            // While there are activities pausing we skipping starting any new activities until
            // pauses are complete. NOTE: that we also do this for activities that are starting in
            // the paused state because they will first be resumed then paused on the client side.
            if (DEBUG_SWITCH || DEBUG_PAUSE || DEBUG_STATES) Slog.v(TAG_PAUSE,
                    "realStartActivityLocked: Skipping start of r=" + r
                    + " some activities pausing...");
            return false;
        }

         ......
             //注釋2
             // Create activity launch transaction.   
                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.
                mService.getLifecycleManager().scheduleTransaction(clientTransaction);
          ......

在clientTransaction .addCallback()的是傳進(jìn)去的就是ClientTransactionItem耕挨,可以直接搜索 ClientTransaction 的 addCallback()方法:

    public void addCallback(ClientTransactionItem activityCallback) {
        if (mActivityCallbacks == null) {
            mActivityCallbacks = new ArrayList<>();
        }
        mActivityCallbacks.add(activityCallback);
    }

確實(shí)是ClientTransactionItem類(lèi)型的參數(shù),那就可以直接看傳進(jìn)去的實(shí)現(xiàn)類(lèi)LaunchActivityItem的excute方法:

    @Override
    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);
        client.handleLaunchActivity(r, pendingActions, null /* customIntent */);   //注釋1
        Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
    }

最后執(zhí)行了注釋1的 client.handleLaunchActivity(r, pendingActions, null /* customIntent */)語(yǔ)句尉桩,那應(yīng)該找ClientTransactionHandler類(lèi)中的handleLaunchActivity方法筒占,但是ClientTransactionHandler是一個(gè)抽象類(lèi),所以需要找到其實(shí)現(xiàn)類(lèi)蜘犁。在前面分析ActivityThread的時(shí)候翰苫,在Hanlder收到EXECUTE_TRANSACTION的消息的時(shí)候:

             case EXECUTE_TRANSACTION:
                    final ClientTransaction transaction = (ClientTransaction) msg.obj;
                    mTransactionExecutor.execute(transaction);   //注釋1
                    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;

在執(zhí)行注釋1的時(shí)候,我們可以看變量mTransactionExecutor是如何初始化的:

    private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);

可以看到是直接new了一個(gè)實(shí)例这橙,并且傳了this奏窑,也就是ActivityThread的對(duì)象進(jìn)去,而ActivityThread繼承與ClientTransactionHandler屈扎,所以 在執(zhí)行語(yǔ)句client.handleLaunchActivity(r, pendingActions, null /* customIntent */)的時(shí)候埃唯,實(shí)際上執(zhí)行的是ActivityThread的handleLaunchActivity方法,接下來(lái)我們返回ActivityThread來(lái)查看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();
        }
        WindowManagerGlobal.initialize();

        final Activity a = performLaunchActivity(r, customIntent);   //注釋1

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

繼續(xù)查上面注釋1的代碼:

  private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {

        ......

       //創(chuàng)建Activity的Context
        ContextImpl appContext = createBaseContextForActivity(r);
        Activity activity = null;
        try {
            //利用類(lèi)加載器來(lái)創(chuàng)建Activity實(shí)例
            java.lang.ClassLoader cl = appContext.getClassLoader();
            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);
            }
        }

          ......
     //執(zhí)行Activity的attach方法
    activity.attach(appContext, this, getInstrumentation(), r.token,
                        r.ident, app, r.intent, r.activityInfo, title, r.parent,
                        r.embeddedID, r.lastNonConfigurationInstances, config,
                        r.referrer, r.voiceInteractor, window, r.configCallback);

          ......

        if (r.isPersistable()) {
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);                       //注釋1
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);   //注釋2
                }


        return activity;

}

無(wú)論看注釋1還是注釋2鹰晨,調(diào)用過(guò)程也是一樣的墨叛,所以繼續(xù)沿著注釋1查看代碼:

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

終于看到 activity.performCreate(icicle)這么一行語(yǔ)句了滑沧,想哭~~~
直接搜索Activity的performCreate方法:

 final void performCreate(Bundle icicle, PersistableBundle persistentState) {
        mCanEnterPictureInPicture = true;
        restoreHasCurrentPermissionRequest(icicle);
        if (persistentState != null) {
            onCreate(icicle, persistentState);
        } else {
            onCreate(icicle);
        }
        writeEventLog(LOG_AM_ON_CREATE_CALLED, "performCreate");
        mActivityTransitionState.readState(icicle);

        mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
                com.android.internal.R.styleable.Window_windowNoDisplay, false);
        mFragments.dispatchActivityCreated();
        mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
    }

終于、終于巍实、終于滓技,兜兜轉(zhuǎn)轉(zhuǎn)十幾個(gè)類(lèi),終于找到onCreate方法了E锪省A钇!也終于知道為什么onCreate會(huì)有兩個(gè)重載的方法了丸边,也終于知道為什么會(huì)執(zhí)行一個(gè)參數(shù)的onCreate()的方法而不是兩個(gè)參數(shù)的了5亍!妹窖!至此Activity啟動(dòng)流程終于告一段落了纬朝。如是文章有述說(shuō)不不正確的地方,歡迎來(lái)騷骄呼,我會(huì)及時(shí)更新的共苛!

總結(jié)

1、在分析Activity的啟動(dòng)過(guò)程中蜓萄,我斷斷續(xù)續(xù)看了大概兩周隅茎,如果按照一天看五個(gè)小時(shí)來(lái)算,應(yīng)該4天左右嫉沽。一開(kāi)始眼睛都疼辟犀,完全懵逼撞秋,不知道該怎么找關(guān)鍵點(diǎn)來(lái)看舶治,后來(lái)一邊看別人的博客是怎么分析的,一邊自己跟著點(diǎn)著來(lái)看郊艘,慢慢就熟悉了玻佩。
2出嘹、在分析源碼的過(guò)程中,先掌握大概的流程脈絡(luò)夺蛇,不必細(xì)究代碼疚漆,一來(lái)可以培養(yǎng)自信心和興趣酣胀,二來(lái)也比較快熟悉過(guò)程刁赦。等熟悉大概的流程之后就可以分析Activity的啟動(dòng)模式是怎么處理的、如何創(chuàng)建闻镶、關(guān)聯(lián)任務(wù)棧甚脉、如何檢查權(quán)限等等。否則一開(kāi)始就細(xì)究這些細(xì)節(jié)铆农,很難進(jìn)行下一步牺氨,也打擊自信心狡耻,得不償失。
3猴凹、由于源碼牽涉的類(lèi)比較多夷狰,過(guò)程也比較復(fù)雜,回調(diào)也是看得懵逼郊霎,所以建議在看的時(shí)候最好動(dòng)手畫(huà)一下流程圖沼头,這樣思路比較清晰,看起來(lái)也不會(huì)到處找來(lái)找去的书劝。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末进倍,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子购对,更是在濱河造成了極大的恐慌猾昆,老刑警劉巖,帶你破解...
    沈念sama閱讀 207,113評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件骡苞,死亡現(xiàn)場(chǎng)離奇詭異垂蜗,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)解幽,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,644評(píng)論 2 381
  • 文/潘曉璐 我一進(jìn)店門(mén)么抗,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人亚铁,你說(shuō)我怎么就攤上這事蝇刀。” “怎么了徘溢?”我有些...
    開(kāi)封第一講書(shū)人閱讀 153,340評(píng)論 0 344
  • 文/不壞的土叔 我叫張陵吞琐,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我然爆,道長(zhǎng)站粟,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 55,449評(píng)論 1 279
  • 正文 為了忘掉前任曾雕,我火速辦了婚禮奴烙,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘剖张。我一直安慰自己切诀,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,445評(píng)論 5 374
  • 文/花漫 我一把揭開(kāi)白布搔弄。 她就那樣靜靜地躺著幅虑,像睡著了一般。 火紅的嫁衣襯著肌膚如雪顾犹。 梳的紋絲不亂的頭發(fā)上倒庵,一...
    開(kāi)封第一講書(shū)人閱讀 49,166評(píng)論 1 284
  • 那天褒墨,我揣著相機(jī)與錄音,去河邊找鬼擎宝。 笑死郁妈,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的绍申。 我是一名探鬼主播圃庭,決...
    沈念sama閱讀 38,442評(píng)論 3 401
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼失晴!你這毒婦竟也來(lái)了剧腻?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 37,105評(píng)論 0 261
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤涂屁,失蹤者是張志新(化名)和其女友劉穎书在,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體拆又,經(jīng)...
    沈念sama閱讀 43,601評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡儒旬,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,066評(píng)論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了帖族。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片栈源。...
    茶點(diǎn)故事閱讀 38,161評(píng)論 1 334
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖竖般,靈堂內(nèi)的尸體忽然破棺而出甚垦,到底是詐尸還是另有隱情,我是刑警寧澤涣雕,帶...
    沈念sama閱讀 33,792評(píng)論 4 323
  • 正文 年R本政府宣布艰亮,位于F島的核電站,受9級(jí)特大地震影響挣郭,放射性物質(zhì)發(fā)生泄漏迄埃。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,351評(píng)論 3 307
  • 文/蒙蒙 一兑障、第九天 我趴在偏房一處隱蔽的房頂上張望侄非。 院中可真熱鬧,春花似錦流译、人聲如沸逞怨。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,352評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)骇钦。三九已至,卻和暖如春竞漾,著一層夾襖步出監(jiān)牢的瞬間眯搭,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,584評(píng)論 1 261
  • 我被黑心中介騙來(lái)泰國(guó)打工业岁, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留鳞仙,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 45,618評(píng)論 2 355
  • 正文 我出身青樓笔时,卻偏偏與公主長(zhǎng)得像棍好,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子允耿,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,916評(píng)論 2 344

推薦閱讀更多精彩內(nèi)容