Activity的啟動(dòng)流程這一篇夠了

Activity啟動(dòng).png

來(lái)了小伙子门怪,先自我介紹一下吧

  • 我叫***, 我精通Android系統(tǒng)的.....

什么笆豁?你精通Android系統(tǒng)?來(lái)森瘪,你給我說(shuō)下Activity的啟動(dòng)流程。

Activity的啟動(dòng)過(guò)程是系統(tǒng)中比較有代表意義的過(guò)程票堵,涉及到了各個(gè)進(jìn)程之間的相互交互扼睬,以及生命周期的回調(diào)控制,這也是為什么在面試過(guò)程出現(xiàn)頻率這么高的原因之一换衬。

Activity的啟動(dòng)流程在API28以后變成了事務(wù)啟動(dòng)的方式痰驱,相比之前版本的邏輯有了一些變化,但是萬(wàn)變不離其宗瞳浦,大致流程還是類似的担映,只是增加了一些類,用來(lái)更好的劃分職責(zé)叫潦,更優(yōu)的處理邏輯蝇完。


在開(kāi)始之前,我們先簡(jiǎn)單普及下基礎(chǔ)知識(shí)矗蕊。

Activity 啟動(dòng)主要涉及到3個(gè)進(jìn)程短蜕。

    1. 系統(tǒng)進(jìn)程 SystemServer (負(fù)責(zé)管理整個(gè)framework,是Zygote孵化的第一個(gè)進(jìn)程)
    1. App進(jìn)程(App進(jìn)程是用戶點(diǎn)擊桌面icon時(shí)傻咖,通過(guò)Launcher進(jìn)程請(qǐng)求SystemServer朋魔,再調(diào)用Zygote孵化的)
    1. Zygote進(jìn)程(所有進(jìn)程孵化都由Zygote完成,而Zygote是init進(jìn)程的子進(jìn)程卿操,也由init進(jìn)程孵化)
    1. 如果點(diǎn)擊桌面icon啟動(dòng)還會(huì)涉及到 Launcher進(jìn)程(Zygote孵化的第一個(gè)應(yīng)用進(jìn)程)

進(jìn)程之間靠什么通信警检?

我們都知道進(jìn)程與進(jìn)程之間是數(shù)據(jù)隔離的,無(wú)法相互訪問(wèn)數(shù)據(jù)害淤,所以進(jìn)程之間通信是靠Binder來(lái)完成的扇雕。

面試官可能會(huì)問(wèn)你 為什么會(huì)用Binder通信,Binder相比Socket有什么優(yōu)勢(shì)呢窥摄?

  • 我想都沒(méi)想直接說(shuō) 1次拷貝镶奉,因?yàn)?次拷貝啊

然而果然被追問(wèn)了 為啥Binder能做到1次拷貝,而其他的技術(shù)是2次拷貝

  • 我當(dāng)時(shí)比較年輕,雖然我不知道具體細(xì)節(jié)哨苛,但是我知道內(nèi)存映射鸽凶。
    我直接拍腦門就扯 因?yàn)锽inder在server端于內(nèi)核中通過(guò)mmap技術(shù)建立了內(nèi)存映射,當(dāng)我們Client與Server通信的時(shí)候建峭,只需要把Client端的通信數(shù)據(jù)拷貝到內(nèi)核中與Server映射好的內(nèi)存區(qū)域就相當(dāng)于拷貝到Server端了........

好吱瘩,可以描述下具體的映射怎么做的么?....

  • 大大大哥迹缀,我真不知道了使碾。。祝懂。票摇。

這里我推薦一篇Binder的文章,我認(rèn)為是大量介紹Binder的博客中描述的很透徹的砚蓬,沒(méi)有廢話矢门,適合急性子。有興趣的同學(xué)可以學(xué)習(xí)以下灰蛙,防止面試的時(shí)候跟我一樣叫大哥祟剔。
Android Binder通信一次拷貝你真的理解了嗎?


Activity啟動(dòng)流程主要包含幾步摩梧?

我們以點(diǎn)擊Launcher的一個(gè)icon為開(kāi)始物延,整體扯一下Activity的啟動(dòng)過(guò)程,桌面其實(shí)就是LauncherApp的一個(gè)Activity

    1. 當(dāng)點(diǎn)擊Launcher的icon開(kāi)始仅父,Launcher進(jìn)程會(huì)像AMS發(fā)送點(diǎn)擊icon的啟動(dòng)信息(這些信息就是在AndroidMainifest.xml中<intent-filter>標(biāo)簽定義的啟動(dòng)信息叛薯,數(shù)據(jù)由PackageManagerService解析出來(lái))
    1. AMS收到信息后會(huì)先后經(jīng)過(guò)ActivityTaskManagerService->ActivityStartController->ActivityStarter內(nèi)部類Request,然后把信息存到Request中笙纤,并通知Launcher進(jìn)程讓Activity休眠(補(bǔ)充個(gè)小知識(shí)點(diǎn)耗溜,這個(gè)過(guò)程會(huì)檢測(cè)Activity在AndroidMainifest.xml的注冊(cè),如果沒(méi)有注冊(cè)就報(bào)錯(cuò)了)
    1. Launcher進(jìn)程的ApplicationThread對(duì)象收到消息后調(diào)用handlePauseActivity()進(jìn)行暫停省容,并通知AMS已經(jīng)暫停抖拴。
      實(shí)現(xiàn)細(xì)節(jié):ActivityThread.sendMessage()通過(guò)ActivityThread的H類發(fā)送Handler消息,然后觸發(fā) mTransactionExecutor.execute(transaction)腥椒,
      執(zhí)行過(guò)程中依賴ActivityClientRecord.mLifecycleState數(shù)值并通過(guò)ClientTransactionHandler抽象類的實(shí)現(xiàn)(ActivityThread)進(jìn)行分發(fā)阿宅。
      注 :ActivityClientRecord.mLifecycleState(-1 ~ 7分別代表 UNDEFINED, PRE_ON_CREATE, ON_CREATE, ON_START, ON_RESUME, ON_PAUSE, ON_STOP, ON_DESTROY, ON_RESTART)
    1. AMS收到Launcher的已暫停消息后,會(huì)檢查要啟動(dòng)的Activity所在的進(jìn)程是否已經(jīng)啟動(dòng)了寞酿,如果已經(jīng)啟動(dòng)了就打開(kāi)家夺,如果未啟動(dòng)則通過(guò)Process.start(android.app.ActivityThread)來(lái)啟動(dòng)一個(gè)新的進(jìn)程脱柱。
    1. 進(jìn)程創(chuàng)建好以后伐弹,會(huì)調(diào)用ActivityThread.main(),初始化MainLooper,并創(chuàng)建Application對(duì)象。然后Instrumentation.newApplication()反射創(chuàng)建Application惨好,創(chuàng)建ContextImpl通過(guò)Application的attach方法與Application進(jìn)行綁定煌茴,最終會(huì)調(diào)用Instrumentation.callApplicationOnCreate執(zhí)行Application的onCreate函數(shù)進(jìn)行一些初始化的工作。完成后會(huì)通知AMS進(jìn)程已經(jīng)啟動(dòng)好了日川。
      通知過(guò)程:通過(guò)IActivityManager.attachApplication(IApplicationThread thread, long startSeq)蔓腐,將Application對(duì)象傳入AMS
    1. AMS收到app進(jìn)程啟動(dòng)成功的消息后,從ActivityTaskManagerService中取出對(duì)應(yīng)的Activity啟動(dòng)信息龄句, 并通過(guò)ApplicationThreadProxy對(duì)象回论,調(diào)用其scheduleTransaction(ClientTransaction transaction)方法,具體要啟動(dòng)的Activity都在ClientTransaction對(duì)象中分歇。
    1. app進(jìn)程的ApplicationThread收到消息后會(huì)調(diào)用ActiivtyThread.sendMessage()傀蓉,通過(guò)H發(fā)送Handler消息,在handleMessage方法的內(nèi)部又會(huì)調(diào)用 mTransactionExecutor.execute(transaction);具體參考第3步
      最終調(diào)用performLaunchActivity方法創(chuàng)建activity和context并將其做關(guān)聯(lián)职抡,然后通過(guò)mInstrumentation.callActivityOnCreate()->Activity.performCreate()->Activity.onCreate()回調(diào)到了Activity的生命周期葬燎。

Activity啟動(dòng)過(guò)程主要涉及哪些類

  • 為了防止后續(xù)大量的源碼分析過(guò)程中影響整體的鏈路關(guān)系,在分析完源碼后缚甩,我總結(jié)了一下相關(guān)類谱净,以及調(diào)用方法,具體看以下描述擅威。

啟動(dòng)一個(gè)Activity一般通過(guò)startActivity()

startActivity(new Intent(OneActivity.this,TwoActivity.class));
  • Activity
    startActivity()
    startActivityForResult()

  • Instrumentation 用于實(shí)現(xiàn)應(yīng)用程序檢測(cè)代碼的基類壕探。當(dāng)在打開(kāi)程序指令的時(shí)候運(yùn)行,這個(gè)類將在任何應(yīng)用程- 序代碼之前為您實(shí)例化郊丛,可以監(jiān)視系統(tǒng)與應(yīng)用程序的所有交互浩蓉。在AndroidManifest.xml文件的<instrumentation>標(biāo)記。
    execStartActivity()

  • ActivityManagerService
    startActivity()
    startActivityAsUser()

  • ActivityStarter 用于解釋如何啟動(dòng)活動(dòng)宾袜。此類記錄所有邏輯捻艳,用于確定如何將意圖和標(biāo)志轉(zhuǎn)換為Activity以及關(guān)聯(lián)的任務(wù)和堆棧。
    execute()
    startActivity()
    startActivityUnchecked()

  • ActivityStackSupervisor
    resumeFocusedStackTopActivityLocked()

  • ActivityStack 單個(gè)Activity堆棧的狀態(tài)和管理
    resumeTopActivityUncheckedLocked()
    resumeTopActivityInnerLocked()

  • ActivityStackSupervisor Activity堆棧管理
    startSpecificActivityLocked()
    realStartActivityLocked()

  • ClientTransaction 一種容器庆猫,它保存一系列消息(比如聲明周期的狀態(tài))认轨,這些消息可以發(fā)送給client。
    ClientTransaction.obtain(app.thread, r.appToken)//初始化
    addCallback((LaunchActivityItem.obtain(new Intent(r.intent),...)

  • ClientLifecycleManager //該類能夠組合多個(gè)client生命周期轉(zhuǎn)換請(qǐng)求/回調(diào)月培,并將它們作為單個(gè)事務(wù)執(zhí)行
    scheduleTransaction(clientTransaction)

  • ClientTransaction
    schedule()

  • ApplicationThread
    scheduleTransaction()

  • ActivityThread 它管理應(yīng)用程序進(jìn)程中主線程中執(zhí)行的調(diào)度和執(zhí)行活動(dòng)嘁字、廣播以及活動(dòng)管理器請(qǐng)求的其他操作。
    scheduleTransaction()
    sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);

  • ClientTransactionHandler //ActivityThread 繼承 ClientTransactionHandler杉畜,所以調(diào)用了父類scheduleTransaction()
    scheduleTransaction()

  • TransactionExecutor 以正確的順序管理事務(wù)執(zhí)行
    execute()
    executeCallbacks()
    transaction.getCallbacks().get(i).execute()

  • LaunchActivityItem 請(qǐng)求啟動(dòng)Activity
    execute()

  • ActivityThread
    handleLaunchActivity()
    performLaunchActivity()

  • Instrumentation
    callActivityOnCreate()

  • Activity
    onCreate()


源碼層分析整個(gè)鏈路

我們先看下正常啟動(dòng)Activity的方式纪蜒,一般我們都會(huì)通過(guò)以下的方式啟動(dòng)一個(gè)新的Activity。

startActivity(new Intent(OneActivity.this,TwoActivity.class));

其實(shí)這是在Activity中的調(diào)用方式此叠,調(diào)用的即是父類Activity的startActivity()方法,因參數(shù)不同分為兩個(gè)方法纯续,具體如下

  @Override
    public void startActivity(Intent intent) {
        this.startActivity(intent, null);
    }

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

最終調(diào)用的是startActivityForResult()

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

public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
            @Nullable Bundle options) {
        if (mParent == null) {
            options = transferSpringboardActivityOptions(options);
            Instrumentation.ActivityResult ar =
                //主要看這里mInstrumentation為Instrumentation對(duì)象
                mInstrumentation.execStartActivity(
                    this, mMainThread.getApplicationThread(), mToken, this,
                    intent, requestCode, 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);
            }
        }
    }

核心邏輯是調(diào)用了Instrumentation.execStartActivity()

  public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {
       ...
        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);
            checkStartActivityResult(result, intent);
        } catch (RemoteException e) {
            throw new RuntimeException("Failure from system", e);
        }
        return null;
    }

ActivityManager.getService()這個(gè)獲取的是誰(shuí)?
邏輯是從IActivityManagerSingleton.get()獲取,那IActivityManagerSingleton又是誰(shuí)猬错?
IActivityManagerSingleton是這么定義的Singleton<IActivityManager> IActivityManagerSingleton
get取出來(lái)的是IActivityManager,看這個(gè)大寫(xiě)I開(kāi)頭就知道是一個(gè)接口窗看,實(shí)際調(diào)用過(guò)的是它的實(shí)現(xiàn)ActivityManagerService。
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.
        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實(shí)際調(diào)用的是ActivityStarter.execute(),連帶調(diào)用到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();
            result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
                    startFlags, doResume, options, inTask, outActivity);
        } finally {
            ...     
        }
        postStartActivityProcessing(r, result, mTargetStack);
        return result;
    }

ActivityStarter.startActivityUnchecked()連帶調(diào)用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;
    }

targetStack為ActivityStack對(duì)象倦炒,ActivityStack.resumeTopActivityUncheckedLocked()

 boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
        if (mStackSupervisor.inResumeTopActivity) {
            // 防止遞歸的
            return false;
        }

        boolean result = false;
        try {
            // Protect against recursion.
            mStackSupervisor.inResumeTopActivity = true;
            //主要看這
            result = resumeTopActivityInnerLocked(prev, options);
            if (next == null || !next.canTurnScreenOn()) {
                checkReadyForSleep();
            }
        } finally {
            mStackSupervisor.inResumeTopActivity = false;
        }

        return result;
    }

ActivityStack.resumeTopActivityInnerLocked()調(diào)用了mStackSupervisor.startSpecificActivityLocked(next, true, true);其中mStackSupervisor為ActivityStackSupervisor显沈。
ActivityStackSupervisor.startSpecificActivityLocked()中調(diào)用
ActivityStackSupervisor.realStartActivityLocked()

  final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
            boolean andResume, boolean checkConfig) throws RemoteException {
...
  // Schedule transaction.
   mService.getLifecycleManager().scheduleTransaction(clientTransaction);
}

注意這個(gè)clientTransaction對(duì)象,通過(guò)這種方式初始化

    //app.thread為IApplicationThread  
    final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,  r.appToken);

     // 注意下這個(gè)LaunchActivityItem.obtain
    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));

ClientLifecycleManager.scheduleTransaction(clientTransaction);

    void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
        final IApplicationThread client = transaction.getClient();
        transaction.schedule();
        if (!(client instanceof Binder)) { 
            transaction.recycle();
        }
    }

transaction.schedule();就要找到

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

mClient即是以上描述的ApplicationThread,因此我們跟進(jìn)ApplicationThread.scheduleTransaction()

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

我靠逢唤,調(diào)用了ActivityThread.scheduleTransaction(transaction),但是ActivityThread并沒(méi)有scheduleTransaction(),所以我們找他繼承的類ClientTransactionHandler拉讯,發(fā)現(xiàn)ClientTransactionHandler果然有scheduleTransaction()

   /** Prepare and schedule transaction for execution. */
    void scheduleTransaction(ClientTransaction transaction) {
        transaction.preExecute(this);
        sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
    }

以上消息通過(guò)ActivityThread H對(duì)象進(jìn)行發(fā)送具體解析也在ActivityThread中

  case EXECUTE_TRANSACTION:
                    final ClientTransaction transaction = (ClientTransaction) msg.obj;
                    mTransactionExecutor.execute(transaction);
                    if (isSystem()) { 
                        transaction.recycle();
                    }
                    // TODO(lifecycler): Recycle locally scheduled transactions.
                    break;

我們可以看下TransactionExecutor.execute(transaction);

    //首先,所有回調(diào)將按照它們?cè)诹斜碇谐霈F(xiàn)的順序執(zhí)行鳖藕。如果回調(diào)需要特定的執(zhí)行前或執(zhí)行后狀態(tài)遂唧,
   //則客戶端將相應(yīng)地進(jìn)行轉(zhuǎn)換。然后客戶端將循環(huán)到最終的生命周期狀態(tài)(如果提供)吊奢。
   //否則盖彭,它將保持在回調(diào)所需的初始狀態(tài)或最后狀態(tài)。
    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()方法

  /** Transition to the final state if requested by the transaction. */
  public void executeCallbacks(ClientTransaction transaction) {
//transaction.getCallbacks()會(huì)獲取clientTransaction.addCallbacks()的數(shù)據(jù)页滚。
        final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
        if (callbacks == null) {
            // No callbacks to execute, return early.
            return;
        }
        log("Resolving callbacks");

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

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

transaction.getCallbacks()就是上述過(guò)程中ClientTransaction創(chuàng)建過(guò)程賦值的LaunchActivityItem對(duì)象召边,因此主要看下LaunchActivityItem.execute()

    @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 */);
        Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
    }

此時(shí)的client為ActivityThread,因此調(diào)用ActivityThread.handleLaunchActivity()

   @Override
    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);
...
}
 /**  Core implementation of activity launch. */
    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        ActivityInfo aInfo = r.activityInfo;
        if (r.packageInfo == null) {
            r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
                    Context.CONTEXT_INCLUDE_CODE);
        }

        ComponentName component = r.intent.getComponent();
        if (component == null) {
            component = r.intent.resolveActivity(
                mInitialApplication.getPackageManager());
            r.intent.setComponent(component);
        }

        if (r.activityInfo.targetActivity != null) {
            component = new ComponentName(r.activityInfo.packageName,
                    r.activityInfo.targetActivity);
        }

        ContextImpl appContext = createBaseContextForActivity(r);
        Activity activity = null;
        try {
            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) {
        ...
            }
        }

        try {
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);
          ...
                activity.mCalled = false;
                if (r.isPersistable()) {
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }
                if (!activity.mCalled) {     
                }
                r.activity = activity;
            }
            r.setState(ON_CREATE);
            mActivities.put(r.token, r);
        } catch (SuperNotCalledException e) {
            throw e;
        } catch (Exception e) {
            }
        }

        return activity;
    }

主要跟進(jìn)mInstrumentation.callActivityOnCreate()

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

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

至此已經(jīng)回調(diào)到了Activity的onCreate()方法裹驰,Activity也就正式啟動(dòng)了隧熙,后續(xù)就是對(duì)應(yīng)的聲明周期回調(diào)。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末幻林,一起剝皮案震驚了整個(gè)濱河市贞盯,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌沪饺,老刑警劉巖躏敢,帶你破解...
    沈念sama閱讀 206,214評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異整葡,居然都是意外死亡件余,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,307評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門遭居,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)啼器,“玉大人,你說(shuō)我怎么就攤上這事俱萍《丝牵” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 152,543評(píng)論 0 341
  • 文/不壞的土叔 我叫張陵枪蘑,是天一觀的道長(zhǎng)损谦。 經(jīng)常有香客問(wèn)我岖免,道長(zhǎng),這世上最難降的妖魔是什么成翩? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 55,221評(píng)論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮赦役,結(jié)果婚禮上麻敌,老公的妹妹穿的比我還像新娘。我一直安慰自己掂摔,他們只是感情好术羔,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,224評(píng)論 5 371
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著乙漓,像睡著了一般级历。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上叭披,一...
    開(kāi)封第一講書(shū)人閱讀 49,007評(píng)論 1 284
  • 那天寥殖,我揣著相機(jī)與錄音,去河邊找鬼涩蜘。 笑死嚼贡,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的同诫。 我是一名探鬼主播粤策,決...
    沈念sama閱讀 38,313評(píng)論 3 399
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼误窖!你這毒婦竟也來(lái)了叮盘?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 36,956評(píng)論 0 259
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤霹俺,失蹤者是張志新(化名)和其女友劉穎柔吼,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體丙唧,經(jīng)...
    沈念sama閱讀 43,441評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡嚷堡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,925評(píng)論 2 323
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了艇棕。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片蝌戒。...
    茶點(diǎn)故事閱讀 38,018評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖沼琉,靈堂內(nèi)的尸體忽然破棺而出北苟,到底是詐尸還是另有隱情,我是刑警寧澤打瘪,帶...
    沈念sama閱讀 33,685評(píng)論 4 322
  • 正文 年R本政府宣布友鼻,位于F島的核電站傻昙,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏彩扔。R本人自食惡果不足惜妆档,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,234評(píng)論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望虫碉。 院中可真熱鬧贾惦,春花似錦、人聲如沸敦捧。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,240評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)兢卵。三九已至习瑰,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間秽荤,已是汗流浹背甜奄。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,464評(píng)論 1 261
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留窃款,地道東北人贺嫂。 一個(gè)月前我還...
    沈念sama閱讀 45,467評(píng)論 2 352
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像雁乡,于是被迫代替她去往敵國(guó)和親第喳。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,762評(píng)論 2 345

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