Activity啟動(dòng)流程源碼解析

Activity的啟動(dòng)流程一般可以分為兩種,一種是應(yīng)用程序根Activity的啟動(dòng)翼馆,而另一種則是普通Activity的啟動(dòng)。根Activity的啟動(dòng)是指應(yīng)用程序啟動(dòng)后展示的第一個(gè)Activity(即intent-filter里面對(duì)應(yīng)的action為MAIN,category為L(zhǎng)AUNCHER的Activity),因此啟動(dòng)這種Activity可以理解為啟動(dòng)應(yīng)用程序谐丢,其啟動(dòng)過(guò)程也就是應(yīng)用程序的啟動(dòng)過(guò)程爽航。普通Activity的啟動(dòng)是指應(yīng)用程序進(jìn)程已經(jīng)啟動(dòng)蚓让,啟動(dòng)一個(gè)除根Activity之外的其它Activity。

本文主要介紹普通Activity啟動(dòng)過(guò)程的源碼分析讥珍,而且源碼版本基于Android 8.0历极。至于根Activity的啟動(dòng)過(guò)程(即應(yīng)用程序的啟動(dòng)過(guò)程),其啟動(dòng)過(guò)程與普通Activity啟動(dòng)過(guò)程是有重疊的衷佃,有興趣的可以自己去閱讀源碼了解一下趟卸,從LauncherActivity的onListItemClick()方法開(kāi)始。

普通Activity的啟動(dòng)流程可以分為一下3個(gè)步驟:

  • 啟動(dòng)Activity請(qǐng)求AMS過(guò)程
  • AMS到ApplicationThread調(diào)用過(guò)程
  • ActivityThread啟動(dòng)Activity過(guò)程

一氏义、啟動(dòng)Activity請(qǐng)求AMS過(guò)程

啟動(dòng)Activity時(shí)會(huì)調(diào)用startActivity方法锄列,那我們就從Activity的startActivity(Intent intent)方法開(kāi)始吧:

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

我們看到這個(gè)startActivity(Intent intent)方法又會(huì)去調(diào)用重載的startActivity(Intent intent, @Nullable Bundle options)方法:

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

由于這里我們傳入的options為null,所以轉(zhuǎn)而調(diào)用startActivityForResult(intent, -1)方法惯悠,之后最終又會(huì)調(diào)用到startActivityForResult(@RequiresPermission Intent intent, int requestCode,
@Nullable Bundle options)方法:

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

這里我們只重點(diǎn)關(guān)注Activity啟動(dòng)相關(guān)部分邻邮,由于我們是第一次啟動(dòng)Activity,所以這里的mParent為空克婶,執(zhí)行該if分支筒严,然后調(diào)用Instrumentation的execStartActivity()方法:

    public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {
        ... ...
        try {
            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;
    }

我們這里先簡(jiǎn)單了解一下Instrumentation丹泉,Instrumentation主要用來(lái)監(jiān)控應(yīng)用程序和系統(tǒng)的交互,Activity在應(yīng)用進(jìn)程端的啟動(dòng)實(shí)際上就是通過(guò)Instrumentation來(lái)執(zhí)行具體的操作鸭蛙。同樣摹恨,我們只關(guān)注重點(diǎn)部分,發(fā)現(xiàn)在這個(gè)方法中主要調(diào)用ActivityManager.getService()的startActivity方法娶视。那么晒哄,我們就需要通過(guò)源碼具體看下ActivityManager.getService()返回的到底是哈,具體源碼在ActivityManager類中肪获,如下:

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

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

看到這里揩晴,了解過(guò)Android中Binder機(jī)制的同學(xué)一下子應(yīng)該就明白了,調(diào)用ActivityManager的getService()方法獲取到的是AMS(ActivityManagerService)在本地的代理對(duì)象贪磺。順便說(shuō)一下硫兰,這個(gè)源碼是基于Android 8.0的,采用的是AIDL的實(shí)現(xiàn)方式寒锚,這與之前的實(shí)現(xiàn)方式略微有些差別劫映,Android 8.0之前是通過(guò)ActivityManagerNative.getDefault()來(lái)獲取AMS的代理對(duì)象的。

那么刹前,我們回到Instrumentation的execStartActivity()方法泳赋,現(xiàn)在應(yīng)該就很明確了,該方法最終的目的是要調(diào)用AMS的startActivity()方法喇喉。接下來(lái)祖今,我們的任務(wù)就是分析在AMS中的具體調(diào)用過(guò)程。

二拣技、AMS到ApplicationThread調(diào)用過(guò)程

由上面的分析可知千诬,應(yīng)用程序開(kāi)啟一個(gè)普通Activity,在經(jīng)過(guò)Instrumentation的execStartActivity()方法調(diào)用后膏斤,通過(guò)Binder機(jī)制徐绑,會(huì)跨進(jìn)程調(diào)用到SystemServer進(jìn)程AMS的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());
    }

該方法又會(huì)繼續(xù)調(diào)用startActivityAsUser()方法:

    @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) {
        enforceNotIsolatedCaller("startActivity");
        userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
                userId, false, ALLOW_FULL_ONLY, "startActivity", null);
        // TODO: Switch to user app stacks here.
        return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,
                resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
                profilerInfo, null, null, bOptions, false, userId, null, null,
                "startActivityAsUser");
    }

緊接著莫辨,又會(huì)調(diào)用到ActivityStarter類的startActivityMayWait()方法傲茄,該方法實(shí)現(xiàn)代碼較長(zhǎng),同樣我們只挑重點(diǎn)看就可以了:

    final 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, Bundle bOptions, boolean ignoreTargetSecurity, int userId,
            IActivityContainer iContainer, TaskRecord inTask, String reason) {
        ... ...
        int res = startActivityLocked(caller, intent, ephemeralIntent, resolvedType,
                aInfo, rInfo, voiceSession, voiceInteractor,
                resultTo, resultWho, requestCode, callingPid,
                callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
                options, ignoreTargetSecurity, componentSpecified, outRecord, container,
                inTask, reason);
        ... ...
    }

由上面的源碼可知沮榜,startActivityMayWait()方法又會(huì)轉(zhuǎn)而去調(diào)用startActivityLocked()方法:

    int startActivityLocked(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,
            ActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
            ActivityRecord[] outActivity, ActivityStackSupervisor.ActivityContainer container,
            TaskRecord inTask, String reason) {
        ... ...
        mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,
                aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
                callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
                options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,
                container, inTask);
        ... ...
    }

由上面的源碼可知盘榨,startActivityLocked()方法又會(huì)轉(zhuǎn)而去調(diào)用ActivityStarter類的startActivity()方法,同樣我們只關(guān)注重點(diǎn)部分:

    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,
            ActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
            ActivityRecord[] outActivity, ActivityStackSupervisor.ActivityContainer container,
            TaskRecord inTask) {
        ... ...
        return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags, true,
                options, inTask, outActivity);
    }

好吧蟆融,我們看到它又去調(diào)用了startActivity()的另一個(gè)重載方法:

    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 {
            // 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.
            if (!ActivityManager.isStartResultSuccessful(result)
                    && mStartActivity.getTask() != null) {
                mStartActivity.getTask().removeActivity(mStartActivity);
            }
            mService.mWindowManager.continueSurfaceLayout();
        }

        postStartActivityProcessing(r, result, mSupervisor.getLastStack().mStackId,  mSourceRecord,
                mTargetStack);

        return result;
    }

由上面的源碼可知草巡,該方法又去調(diào)用了startActivityUnchecked()方法,同樣只關(guān)注重點(diǎn)部分:

    private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
            ActivityRecord[] outActivity) {
        ... ...
        mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,
                        mOptions);
        ... ...
    }

由上面的源碼可知振愿,該方法又去調(diào)用了ActivityStackSupervisor類的resumeFocusedStackTopActivityLocked()方法:

    boolean resumeFocusedStackTopActivityLocked(
            ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
        if (targetStack != null && isFocusedStack(targetStack)) {
            return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
        }
        final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
        if (r == null || r.state != RESUMED) {
            mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
        } else if (r.state == RESUMED) {
            // Kick off any lingering app transitions form the MoveTaskToFront operation.
            mFocusedStack.executeAppTransition(targetOptions);
        }
        return false;
    }

緊接著捷犹,又會(huì)去調(diào)用ActivityStack類的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);
        } finally {
            mStackSupervisor.inResumeTopActivity = false;
        }
        // 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.
        mStackSupervisor.checkReadyForSleepLocked();

        return result;
    }

緊接著弛饭,又去調(diào)用了resumeTopActivityInnerLocked()方法,該方法代碼很長(zhǎng)萍歉,我們只挑重點(diǎn)看:

    private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
        ... ...
        if (mResumedActivity != null) {
            if (DEBUG_STATES) Slog.d(TAG_STATES,
                    "resumeTopActivityLocked: Pausing " + mResumedActivity);
            // 回調(diào)棧頂Activity的onPause()方法
            pausing |= startPausingLocked(userLeaving, false, next, false);
        }
        ... ...
        mStackSupervisor.startSpecificActivityLocked(next, true, true);
        ... ...
    }

這里侣颂,我們稍微提一下,就是在啟動(dòng)一個(gè)新的Activity之前枪孩,會(huì)先回調(diào)棧頂Activity的onPause()方法憔晒。接著,我們來(lái)看下startSpecificActivityLocked()方法的實(shí)現(xiàn):

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

        r.getStack().setLaunchTime(r);

        if (app != null && app.thread != null) {
        // 應(yīng)用程序進(jìn)程已經(jīng)存在
            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.versionCode,
                            mService.mProcessStats);
                }
                realStartActivityLocked(r, app, andResume, checkConfig);
                return;
            } catch (RemoteException e) {
                Slog.w(TAG, "Exception when starting activity "
                        + r.intent.getComponent().flattenToShortString(), e);
            }

            // If a dead object exception was thrown -- fall through to
            // restart the application.
        }

        // 應(yīng)用程序進(jìn)程不存在蔑舞,則啟動(dòng)應(yīng)用程序進(jìn)程
        mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
                "activity", r.intent.getComponent(), false, false, true);
    }

分析一下startSpecificActivityLocked()源碼拒担,我們可以知道,如果應(yīng)用程序的進(jìn)程已經(jīng)存在的話攻询,就會(huì)去調(diào)用realStartActivityLocked()方法从撼,那么這個(gè)方法代碼也很長(zhǎng),我們依然只關(guān)注重點(diǎn)部分:

    final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
            boolean andResume, boolean checkConfig) throws RemoteException {
        ... ...
        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);
        ... ...
    }

由源碼可知钧栖,這里的app.thread是IApplicationThread低零,同樣是AIDL實(shí)現(xiàn)方式,ActivityThread的內(nèi)部類ApplicationThread繼承了IApplicationThread.Stub拯杠。那么掏婶,這個(gè)很明顯又是通過(guò)Binder機(jī)制進(jìn)行跨進(jìn)程調(diào)用,只不過(guò)現(xiàn)在SystemServer進(jìn)程相當(dāng)于是client端潭陪,App進(jìn)程相當(dāng)于是server端雄妥。

回到realStartActivityLocked()方法,目標(biāo)就很明確了依溯,就是要調(diào)用ActivityThread的scheduleLaunchActivity()方法老厌。接下來(lái),我們的任務(wù)就是分析ActivityThread中啟動(dòng)Activity的過(guò)程誓沸。

三梅桩、ActivityThread啟動(dòng)Activity過(guò)程

由上面的分析可知壹粟,在AMS中經(jīng)過(guò)realStartActivityLocked()方法的調(diào)用后拜隧,通過(guò)Binder機(jī)制,會(huì)跨進(jìn)程調(diào)用到App進(jìn)程中主線程ActivityThread的scheduleLaunchActivity()方法趁仙,從方法名上我們也可以猜出來(lái)是處理啟動(dòng)Activity的洪添,來(lái)看一下具體的源碼:

    @Override
        public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
                ActivityInfo info, Configuration curConfig, Configuration overrideConfig,
                CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor,
                int procState, Bundle state, PersistableBundle persistentState,
                List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
                boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) {

            updateProcessState(procState, false);

            ActivityClientRecord r = new ActivityClientRecord();

            r.token = token;
            r.ident = ident;
            r.intent = intent;
            r.referrer = referrer;
            r.voiceInteractor = voiceInteractor;
            r.activityInfo = info;
            r.compatInfo = compatInfo;
            r.state = state;
            r.persistentState = persistentState;

            r.pendingResults = pendingResults;
            r.pendingIntents = pendingNewIntents;

            r.startsNotResumed = notResumed;
            r.isForward = isForward;

            r.profilerInfo = profilerInfo;

            r.overrideConfig = overrideConfig;
            updatePendingConfiguration(curConfig);

            sendMessage(H.LAUNCH_ACTIVITY, r);
        }

可以看到,scheduleLaunchActivity()方法將啟動(dòng)Activity的參數(shù)封裝成ActivityClientRecord對(duì)象雀费,通過(guò)sendMessage()方法向H發(fā)送LAUNCH_ACTIVITY消息干奢。那這個(gè)H明顯就是一個(gè)Handler,事實(shí)上它就是ActivityThread的一個(gè)內(nèi)部類并且繼承Handler盏袄,是App進(jìn)程中主線程的消息管理類忿峻。了解Binder的同學(xué)應(yīng)該知道薄啥,scheduleLaunchActivity()方法的調(diào)用肯定是在Binder線程池中的,所以這里需要使用主線程的Handler將代碼邏輯切換到主線程逛尚。
接下來(lái)垄惧,我們看下H的handleMessage()方法對(duì)LAUNCH_ACTIVITY消息的處理:

    private class H extends Handler {
        ... ...
        public void handleMessage(Message msg) {
            if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
            switch (msg.what) {
                case LAUNCH_ACTIVITY: {
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
                    final ActivityClientRecord r = (ActivityClientRecord) msg.obj;

                    r.packageInfo = getPackageInfoNoCheck(
                            r.activityInfo.applicationInfo, r.compatInfo);
                    handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                } 
                break;
                ... ...
            }
            ... ...
    }

緊接著,會(huì)調(diào)用handleLaunchActivity()方法:

    private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
        ... ...
        Activity a = performLaunchActivity(r, customIntent);

        if (a != null) {
            r.createdConfig = new Configuration(mConfiguration);
            reportSizeConfigurations(r);
            Bundle oldState = r.state;
            handleResumeActivity(r.token, false, r.isForward,
                    !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);
            ... ...
            }
        }
        ... ...
    }

很明顯绰寞,接著又會(huì)去調(diào)用performLaunchActivity()方法到逊,同樣我們只關(guān)注重點(diǎn)部分:

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");

        ActivityInfo aInfo = r.activityInfo;
        if (r.packageInfo == null) {
            r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
                    Context.CONTEXT_INCLUDE_CODE);
        }

        ComponentName component = r.intent.getComponent();
        ... ...
        ContextImpl appContext = createBaseContextForActivity(r);
        Activity activity = null;
        try {
            java.lang.ClassLoader cl = appContext.getClassLoader();
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
        } catch (Exception e) {
            ... ...
            }
        }

        try {
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);

            if (activity != null) {
                ... ...
                activity.attach(appContext, this, getInstrumentation(), r.token,
                        r.ident, app, r.intent, r.activityInfo, title, r.parent,
                        r.embeddedID, r.lastNonConfigurationInstances, config,
                        r.referrer, r.voiceInteractor, window, r.configCallback);
                ... ...
                activity.mCalled = false;
                if (r.isPersistable()) {
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }
                ... ...
                if (!r.activity.mFinished) {
                    // 回調(diào)onStart()方法
                    activity.performStart();
                    r.stopped = false;
                }             
            }
            mActivities.put(r.token, r);
        } catch (SuperNotCalledException e) {
            throw e;
        } catch (Exception e) {
            ... ...
        }
        return activity;
    }

首先,我們看到Activity的實(shí)例是通過(guò)Instrumentation的newActivity()方法創(chuàng)建的滤钱,而且是通過(guò)反射的方式創(chuàng)建的觉壶,具體實(shí)現(xiàn)如下:

    public Activity newActivity(ClassLoader cl, String className,
            Intent intent)
            throws InstantiationException, IllegalAccessException,
            ClassNotFoundException {
        return (Activity)cl.loadClass(className).newInstance();
    }

其次,我們看到通過(guò)makeApplication()方法創(chuàng)建了應(yīng)用程序的application:

    public Application makeApplication(boolean forceDefaultAppClass,
            Instrumentation instrumentation) {
        if (mApplication != null) {
            return mApplication;
        }
        Application app = null;

        String appClass = mApplicationInfo.className;
        if (forceDefaultAppClass || (appClass == null)) {
            appClass = "android.app.Application";
        }

        try {
            java.lang.ClassLoader cl = getClassLoader();
            ... ...
            ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
            app = mActivityThread.mInstrumentation.newApplication(
                    cl, appClass, appContext);
            appContext.setOuterContext(app);
        } catch (Exception e) {
            ... ...
            }
        }
        mActivityThread.mAllApplications.add(app);
        mApplication = app;

        if (instrumentation != null) {
            try {
                instrumentation.callApplicationOnCreate(app);
            } catch (Exception e) {
                ... ...
                }
            }
        }
        ... ...
        return app;
    }

最后件缸,我們看到通過(guò)調(diào)用Instrumentation的callActivityOnCreate()方法铜靶,回調(diào)啟動(dòng)目標(biāo)Activity的onCreate()方法:

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

緊接著,會(huì)去調(diào)用Activity的performCreate()方法:

   final void performCreate(Bundle icicle) {
        restoreHasCurrentPermissionRequest(icicle);
        onCreate(icicle);
        mActivityTransitionState.readState(icicle);
        performCreateCommon();
    }

看到這里他炊,我們的Activity終于是被啟動(dòng)了旷坦,緊接著它的onStart()和onResume()生命周期方法也會(huì)依次得到回調(diào),至此Activity就呈現(xiàn)在我們眼前了佑稠,那么Activity的啟動(dòng)流程到此為止也就結(jié)束了秒梅。

總結(jié)

普通Activity的啟動(dòng)流程主要涉及了兩個(gè)進(jìn)程,分別是AMS所在SystemServer進(jìn)程和應(yīng)用程序進(jìn)程舌胶,通過(guò)Binder機(jī)制進(jìn)行跨進(jìn)程通信捆蜀,相互配合,最終完成Activity的啟動(dòng)幔嫂。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末辆它,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子履恩,更是在濱河造成了極大的恐慌锰茉,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,378評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件切心,死亡現(xiàn)場(chǎng)離奇詭異飒筑,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)绽昏,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,356評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門协屡,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人全谤,你說(shuō)我怎么就攤上這事肤晓。” “怎么了?”我有些...
    開(kāi)封第一講書人閱讀 152,702評(píng)論 0 342
  • 文/不壞的土叔 我叫張陵补憾,是天一觀的道長(zhǎng)漫萄。 經(jīng)常有香客問(wèn)我,道長(zhǎng)盈匾,這世上最難降的妖魔是什么卷胯? 我笑而不...
    開(kāi)封第一講書人閱讀 55,259評(píng)論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮威酒,結(jié)果婚禮上窑睁,老公的妹妹穿的比我還像新娘。我一直安慰自己葵孤,他們只是感情好担钮,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,263評(píng)論 5 371
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著尤仍,像睡著了一般箫津。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上宰啦,一...
    開(kāi)封第一講書人閱讀 49,036評(píng)論 1 285
  • 那天苏遥,我揣著相機(jī)與錄音,去河邊找鬼赡模。 笑死田炭,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的漓柑。 我是一名探鬼主播教硫,決...
    沈念sama閱讀 38,349評(píng)論 3 400
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼辆布!你這毒婦竟也來(lái)了瞬矩?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書人閱讀 36,979評(píng)論 0 259
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤锋玲,失蹤者是張志新(化名)和其女友劉穎景用,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體惭蹂,經(jīng)...
    沈念sama閱讀 43,469評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡伞插,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,938評(píng)論 2 323
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了剿干。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片蜂怎。...
    茶點(diǎn)故事閱讀 38,059評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖置尔,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情氢伟,我是刑警寧澤榜轿,帶...
    沈念sama閱讀 33,703評(píng)論 4 323
  • 正文 年R本政府宣布幽歼,位于F島的核電站,受9級(jí)特大地震影響谬盐,放射性物質(zhì)發(fā)生泄漏甸私。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,257評(píng)論 3 307
  • 文/蒙蒙 一飞傀、第九天 我趴在偏房一處隱蔽的房頂上張望皇型。 院中可真熱鬧,春花似錦砸烦、人聲如沸弃鸦。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 30,262評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)唬格。三九已至,卻和暖如春颜说,著一層夾襖步出監(jiān)牢的瞬間购岗,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 31,485評(píng)論 1 262
  • 我被黑心中介騙來(lái)泰國(guó)打工门粪, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留喊积,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 45,501評(píng)論 2 354
  • 正文 我出身青樓玄妈,卻偏偏與公主長(zhǎng)得像注服,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子措近,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,792評(píng)論 2 345

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