Android Activity啟動(dòng)源碼及其應(yīng)用

開(kāi)發(fā)中經(jīng)常遇到使用Activity ,網(wǎng)上關(guān)于講解其原理的也很多飘弧,但是都是零零散散,今天想做個(gè)總結(jié),并且也提高一下自己對(duì)源碼的認(rèn)識(shí)

Acitivity 啟動(dòng)過(guò)程

先看入口
最常用的Activity 啟動(dòng)過(guò)程是

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

@Override
public void startActivity(Intent intent, 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);
    }
}

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

其實(shí)我們也可以通過(guò) context.startActivity(next); 來(lái)啟動(dòng)Activity 尝抖,由于Context是抽象類,Activity是Context子類迅皇,所以最后都會(huì)走到上一個(gè)方法牵署。

顯然,從上往下喧半,最終都是由startActivityForResult來(lái)實(shí)現(xiàn)的

public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
    if (mParent == null) {
        //這里會(huì)啟動(dòng)新的Activity奴迅,核心功能都在mMainThread.getApplicationThread()中完成
        Instrumentation.ActivityResult ar =
            mInstrumentation.execStartActivity(
                this, mMainThread.getApplicationThread(), mToken, this,
                intent, requestCode, options);
        if (ar != null) {
            //發(fā)送結(jié)果,即onActivityResult會(huì)被調(diào)用
            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;
        }

        final View decor = mWindow != null ? mWindow.peekDecorView() : null;
        if (decor != null) {
            decor.cancelPendingInputEvents();
        }
        // 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);
        }
    }
}

我們一行一行看,該方法三個(gè)參數(shù)都是正常使用時(shí)用到的取具,我們直接看內(nèi)部脖隶,先去判斷 mParent 是否為空,這個(gè)mParent是什么呢暇检,它其實(shí)是一個(gè)Activity

在Android 4.1以上产阱,可以指定android:parentActivityName="MainActivity"點(diǎn)擊打開(kāi)其他Activity后,可以看到標(biāo)題欄多了一個(gè)返回導(dǎo)航块仆,再點(diǎn)擊標(biāo)題欄的返回時(shí)构蹬,回到MainActivity,而不是回到之前的Task悔据。只在4.1的機(jī)器上有效庄敛,在2.x的機(jī)器上和以前沒(méi)有任何區(qū)別。

<application ... >
    ...
    <activity
        android:name="com.example.myfirstapp.DisplayMessageActivity"
        android:label="@string/title_activity_display_message"
        android:parentActivityName="com.example.myfirstapp.MainActivity" >
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.myfirstapp.MainActivity" />
    </activity>
</application>

一般的Activity其mParent為null科汗,mParent常用在ActivityGroup中藻烤,ActivityGroup已廢棄,而在ActivityGroup內(nèi)部的Activity調(diào)用startActivity的時(shí)候也會(huì)走到上面头滔,內(nèi)部處理邏輯和上面是類似的

也就是說(shuō) 啟動(dòng)新的Activity是在
mInstrumentation.execStartActivity(this,mMainThread.getApplicationThread(), mToken, this, intent, requestCode, options);
這個(gè)方法中怖亭,先不考慮mInstrumentation是做什么的,我們看內(nèi)部實(shí)現(xiàn)

public ActivityResult execStartActivity(
        Context who, IBinder contextThread, IBinder token, Activity target,
        Intent intent, int requestCode, Bundle options) {
    //核心功能在這個(gè)whoThread中完成坤检,其內(nèi)部scheduleLaunchActivity方法用于完成activity的打開(kāi)
    IApplicationThread whoThread = (IApplicationThread) contextThread;
    if (mActivityMonitors != null) {
        synchronized (mSync) {
            final int N = mActivityMonitors.size();
            for (int i=0; i<N; i++) {
                final ActivityMonitor am = mActivityMonitors.get(i);
                if (am.match(who, null, intent)) {
                    am.mHits++;
                    if (am.isBlocking()) {
                        return requestCode >= 0 ? am.getResult() : null;
                    }
                    break;
                }
            }
        }
    }
    try {
        intent.migrateExtraStreamToClipData();
        intent.prepareToLeaveProcess();
        int result = ActivityManagerNative.getDefault()
            .startActivity(whoThread, who.getBasePackageName(), intent,
                    intent.resolveTypeIfNeeded(who.getContentResolver()),
                    token, target != null ? target.mEmbeddedID : null,
                    requestCode, 0, null, null, options);
        //
        checkStartActivityResult(result, intent);
    } catch (RemoteException e) {
    }
    return null;
}

往里面看 contextThread 就是之前傳入的mMainThread.getApplicationThread() 這個(gè)mMainThread 其實(shí)是一個(gè)Binder對(duì)象

ApplicationThread

ApplicationThreadNative

對(duì)于Binder的原理請(qǐng)看 Android進(jìn)程間通信(IPC)機(jī)制Binder簡(jiǎn)要介紹
再回到剛才的源碼兴猩,往下看,先在mActivityMonitors中查找一遍看是否存在這個(gè)activity早歇,如果找到了就跳出循環(huán)峭跳,并且如果可以運(yùn)行就返回監(jiān)控器的結(jié)果。
對(duì)于ActivityMonitor缺前,其實(shí)是是google為了自動(dòng)測(cè)試所添加的一個(gè)類蛀醉,可以說(shuō)是一個(gè)工具類,此處我們不深研究衅码,若想了解請(qǐng)看ActivityMonitor 類的功能

ActivityMonitor

接下來(lái)在try...catch 里就是真正打開(kāi)activity的地方拯刁,核心功能在whoThread中完成

另外提一下checkStartActivityResult(result, intent);這個(gè)方法就是專門拋異常的,它會(huì)對(duì)結(jié)果進(jìn)行檢查逝段,如果無(wú)法打開(kāi)activity垛玻,則拋出諸如ActivityNotFoundException類似的各種異常
如在xml中沒(méi)有注冊(cè)目標(biāo)activity,Unable to find explicit activity class等

    public static void checkStartActivityResult(int res, Object intent) {
        if (res >= ActivityManager.START_SUCCESS) {
            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");
            default:
                throw new AndroidRuntimeException("Unknown error code "
                        + res + " when starting " + intent);
        }
    }

接著上文看奶躯,在try...catch 中首先是要對(duì)傳遞的數(shù)據(jù)做準(zhǔn)備

intent.migrateExtraStreamToClipData();
intent.prepareToLeaveProcess();```
第一個(gè)是將intent里的bundle數(shù)據(jù)進(jìn)行處理以便給底層處理帚桩,
第二句準(zhǔn)備離開(kāi)應(yīng)用程序進(jìn)程,進(jìn)入ActivityManagerService進(jìn)程(意味著bundle的數(shù)據(jù)要在進(jìn)程間傳遞)
*關(guān)于Intent 的機(jī)制請(qǐng)看 [源碼角度輕松學(xué)習(xí)Intent機(jī)制](http://www.reibang.com/p/40ff93eff1a0)*

再接下來(lái)就是我們要關(guān)注的重點(diǎn)了嘹黔,也是真正打開(kāi)activity的地方账嚎,核心功能在whoThread中完成。
    int result = ActivityManagerNative.getDefault()
        .startActivity(whoThread, who.getBasePackageName(), intent,
                intent.resolveTypeIfNeeded(who.getContentResolver()),
                token, target != null ? target.mEmbeddedID : null,
                requestCode, 0, null, null, options);
    //這個(gè)方法是專門拋異常的,它會(huì)對(duì)結(jié)果進(jìn)行檢查郭蕉,如果無(wú)法打開(kāi)activity疼邀,
    //則拋出諸如ActivityNotFoundException類似的各種異常
    checkStartActivityResult(result, intent);
這里 ActivityManagerNative.getDefault() 返回的是一個(gè)IActivityManager接口的代理類,

private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>() {
protected IActivityManager create() {
IBinder b = ServiceManager.getService("activity");
if (false) {
Log.v("ActivityManager", "default service binder = " + b);
}
IActivityManager am = asInterface(b);
if (false) {
Log.v("ActivityManager", "default service = " + am);
}
return am;
}
};
/**
* Cast a Binder object into an activity manager interface, generating
* a proxy if needed.
*/
static public IActivityManager asInterface(IBinder obj) {
if (obj == null) {
return null;
}
IActivityManager in =
(IActivityManager)obj.queryLocalInterface(descriptor);
if (in != null) {
return in;
}

    return new ActivityManagerProxy(obj);
}
這里我把方法提取了一下召锈,也就是說(shuō)返回的是一個(gè)ActivityManagerProxy對(duì)象的引用旁振,其中```ServiceManager.getService("activity");``` 獲取了一個(gè)系統(tǒng)級(jí)的service,而這個(gè)Service 實(shí)質(zhì)上就是ActivityManagerService涨岁,這里就完成了一個(gè)對(duì)ActivityManagerService的代理對(duì)象ActivityManagerProxy的實(shí)例.


>總的來(lái)說(shuō)這里使用的是設(shè)計(jì)模式中的[代理模式](https://github.com/simple-android-framework-exchange/android_design_patterns_analysis/tree/master/proxy/singwhatiwanna), ActivityManagerProxy和ActivityManagerNative 都實(shí)現(xiàn)了IActivityManager拐袜,ActivityManagerProxy 就是代理部分,而ActivityManagerNative 就是真實(shí)部分梢薪,但ActivityManagerNative 是個(gè)抽象類蹬铺,其并不處理過(guò)多的具體邏輯,大部分具體邏輯的實(shí)現(xiàn)由子類ActivityManagerService 承擔(dān)沮尿,ActivityManagerService 是系統(tǒng)級(jí)的Service 并且運(yùn)行于獨(dú)立的進(jìn)程中丛塌,而ActivityManagerProxy 也運(yùn)行于自己的進(jìn)程中较解,因此它們兩個(gè)之間的通信必定是通過(guò)跨進(jìn)程來(lái)進(jìn)行的畜疾,也就是基于Android的Binder機(jī)制,Binder機(jī)制過(guò)于復(fù)雜印衔。
若想了解Binder機(jī)制請(qǐng)參考[[Binder架構(gòu)解析](http://wangkuiwu.github.io/2014/09/01/Binder-Introduce/#anchor1)](http://wangkuiwu.github.io/2014/09/01/Binder-Introduce/)
關(guān)于ActivityManger 請(qǐng)參考[ActivityManger架構(gòu)解析](http://blog.csdn.net/caowenbin/article/details/6036726)
![ActivityManger運(yùn)行機(jī)制](http://upload-images.jianshu.io/upload_images/1212336-9a5c2a630b02f2ca.gif?imageMogr2/auto-orient/strip)

也就是說(shuō)最終是通過(guò)Binder IPC到ActivityManagerService所在進(jìn)程調(diào)用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 options) {
    return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
        resultWho, requestCode, startFlags, profilerInfo, options,
        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 options, int userId) {
    enforceNotIsolatedCaller("startActivity");
    userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
            false, ALLOW_FULL_ONLY, "startActivity", null);
    // TODO: Switch to user app stacks here.
    return mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent,
            resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
            profilerInfo, null, null, options, userId, null, null);
}
>這個(gè)ActivityStackSupervisor類到底是個(gè)啥啡捶?如果仔細(xì)查閱,低版本的Android源碼上是沒(méi)有這個(gè)類的奸焙;后來(lái)AMS的代碼進(jìn)行了部分重構(gòu)瞎暑,關(guān)于Activity棧管理的部分單獨(dú)提取出來(lái)成為了ActivityStackSupervisor類

繼續(xù)往里面看,其內(nèi)部又調(diào)用了[startActivityLocked](http://androidxref.com/5.1.1_r6/xref/frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java#startActivityLocked)方法与帆,這個(gè)方法的作用是在startActivity 前做一系列的檢查了赌,如沒(méi)有在Manifestfest中注冊(cè)拋出的異常

if (err == ActivityManager.START_SUCCESS && aInfo == null) {
// We couldn't find the specific class specified in the Intent.
// Also the end of the line.
err = ActivityManager.START_CLASS_NOT_FOUND;
}
if (err != ActivityManager.START_SUCCESS) {
if (resultRecord != null) {
resultStack.sendActivityResultLocked(-1,
resultRecord, resultWho, requestCode,
Activity.RESULT_CANCELED, null);
}
ActivityOptions.abort(options);
return err;
}

如果啟動(dòng)不成功就返回這個(gè)err,記得在之前mInstrumentation里有個(gè)checkStartActivityResult方法么玄糟,由它來(lái)處理這個(gè)信息勿她,并拋出異常。
>activity 在 AMS 中的形式是 ActivityRecord,task 在 AMS 中的形式為TaskRecord,進(jìn)程在 AMS 中的管理形式為 ProcessRecord
這里還有會(huì)處理Activity 的LaunchMode 啟動(dòng)判斷阵翎,請(qǐng)查看
[Activity LaunchMode源碼分析](http://www.reibang.com/p/09365022adac)
總結(jié)可以看下圖
![Activity 的啟動(dòng)過(guò)程 在ActivityStackSupervisor和ActivityStack 之間的傳遞順序](http://upload-images.jianshu.io/upload_images/1212336-0093b93722c8af42.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

從上圖看出逢并,最后走到了ActivityStackSupervisor中的realStartActivityLocked 方法,這個(gè)方法中有如下的代碼

app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration),
r.compat, r.task.voiceInteractor, app.repProcState, r.icicle, r.persistentState,
results, newIntents, !andResume, mService.isNextTransitionForward(),
profilerInfo);

其中,app.thread的類型為IApplicationThread郭卫,
IApplicationThread 是個(gè)接口砍聊,這個(gè)接口繼承了IInterFace接口,所以它是一個(gè)Binder類型的接口贰军,看到這個(gè)接口里的方法我們可以猜測(cè)這個(gè)接口的實(shí)現(xiàn)類完成了啟動(dòng)activity和service的相關(guān)功能玻蝌,而我們要看其中的實(shí)現(xiàn)方法就要看它的實(shí)現(xiàn)類,還記得上面我們的ApplicationThreadNative么?它繼承了IApplicationThread接口灶伊,其實(shí)他就是這個(gè)接口的實(shí)現(xiàn)類疆前,進(jìn)入這個(gè)類中我們看一下
![ApplicationThread](http://upload-images.jianshu.io/upload_images/1212336-7d22225148fb3891.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
總的來(lái)說(shuō)饒了一圈,Activity的啟動(dòng)最終回到了ApplicationThread中聘萨,ApplicationThread是通過(guò)scheduleLaunchActivity 方法來(lái)啟動(dòng)Activity
    @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);
    }
這里發(fā)送了一個(gè)啟動(dòng)Activity的消息交由Handler處理竹椒,這個(gè)Handler就是H,從sendMessage方法看出米辐,它的作用就是發(fā)送一個(gè)消息給H處理胸完,看一下H對(duì)消息的處理方法
    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);
                Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
            } break;
            case RELAUNCH_ACTIVITY: {
                Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityRestart");
                ActivityClientRecord r = (ActivityClientRecord)msg.obj;
                handleRelaunchActivity(r);
                Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
            } break;
            case PAUSE_ACTIVITY:
                Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
                handlePauseActivity((IBinder)msg.obj, false, (msg.arg1&1) != 0, msg.arg2,
                        (msg.arg1&2) != 0);
                maybeSnapshot();                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                break;
            case PAUSE_ACTIVITY_FINISHING:
                Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
                handlePauseActivity((IBinder)msg.obj, true, (msg.arg1&1) != 0, msg.arg2,
                        (msg.arg1&1) != 0);
                Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                break;
Handler H 對(duì)“LAUNCH_ACTIVITY”  這個(gè)消息處理看出,Activity啟動(dòng)是在handleLaunchActivity(r, null); 方法中實(shí)現(xiàn)的
private void handleLaunchActivity(ActivityClientRecord r, 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
    WindowManagerGlobal.initialize();

    Activity a = performLaunchActivity(r, customIntent);

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

        if (!r.activity.mFinished && r.startsNotResumed) {
            // The activity manager actually wants this one to start out
            // paused, because it needs to be visible but isn't in the
            // foreground.  We accomplish this by going through the
            // normal startup (because activities expect to go through
            // onResume() the first time they run, before their window
            // is displayed), and then pausing it.  However, in this case
            // we do -not- need to do the full pause cycle (of freezing
            // and such) because the activity manager assumes it can just
            // retain the current state it has.
            try {
                r.activity.mCalled = false;
                mInstrumentation.callActivityOnPause(r.activity);
                // We need to keep around the original state, in case
                // we need to be created again.  But we only do this
                // for pre-Honeycomb apps, which always save their state
                // when pausing, so we can not have them save their state
                // when restarting from a paused state.  For HC and later,
                // we want to (and can) let the state be saved as the normal
                // part of stopping the activity.
                if (r.isPreHoneycomb()) {
                    r.state = oldState;
                }
                if (!r.activity.mCalled) {
                    throw new SuperNotCalledException(
                        "Activity " + r.intent.getComponent().toShortString() +
                        " did not call through to super.onPause()");
                }

            } catch (SuperNotCalledException e) {
                throw e;

            } catch (Exception e) {
                if (!mInstrumentation.onException(r.activity, e)) {
                    throw new RuntimeException(
                            "Unable to pause activity "
                            + r.intent.getComponent().toShortString()
                            + ": " + e.toString(), e);
                }
            }
            r.paused = true;
        }
    } else {
        // If there was an error, for any reason, tell the activity
        // manager to stop us.
        try {
            ActivityManagerNative.getDefault()
                .finishActivity(r.token, Activity.RESULT_CANCELED, null, false);
        } catch (RemoteException ex) {
            // Ignore
        }
    }
}
 里面的performLaunchActivity 是真正實(shí)現(xiàn)activity的方法

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);
}
//首先從intent中解析出目標(biāo)activity的啟動(dòng)參數(shù)
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);
}

Activity activity = null;
try {
    java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
    //用ClassLoader(類加載器)將目標(biāo)activity的類通過(guò)類名加載進(jìn)來(lái)并調(diào)用newInstance來(lái)實(shí)例化一個(gè)對(duì)象
    //其實(shí)就是通過(guò)Activity的無(wú)參構(gòu)造方法來(lái)new一個(gè)對(duì)象翘贮,對(duì)象就是在這里new出來(lái)的赊窥。
    activity = mInstrumentation.newActivity(
            cl, component.getClassName(), r.intent);
    StrictMode.incrementExpectedActivityCount(activity.getClass());
    r.intent.setExtrasClassLoader(cl);
    if (r.state != null) {
        r.state.setClassLoader(cl);
    }
} catch (Exception e) {
    if (!mInstrumentation.onException(activity, e)) {
        throw new RuntimeException(
            "Unable to instantiate activity " + component
            + ": " + e.toString(), e);
    }
}

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

    if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
    if (localLOGV) Slog.v(
            TAG, r + ": app=" + app
            + ", appName=" + app.getPackageName()
            + ", pkg=" + r.packageInfo.getPackageName()
            + ", comp=" + r.intent.getComponent().toShortString()
            + ", dir=" + r.packageInfo.getAppDir());

    if (activity != null) {
        Context appContext = createBaseContextForActivity(r, activity);
        CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
        Configuration config = new Configuration(mCompatConfiguration);
        if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
                + r.activityInfo.name + " with config " + config);
        activity.attach(appContext, this, getInstrumentation(), r.token,
                r.ident, app, r.intent, r.activityInfo, title, r.parent,
                r.embeddedID, r.lastNonConfigurationInstances, config);

        if (customIntent != null) {
            activity.mIntent = customIntent;
        }
        r.lastNonConfigurationInstances = null;
        activity.mStartedActivity = false;
        int theme = r.activityInfo.getThemeResource()
        if (theme != 0) {
            activity.setTheme(theme);
        }

        activity.mCalled = false;
        //目標(biāo)activity的onCreate被調(diào)用了,到此為止狸页,Activity被啟動(dòng)了锨能,接下來(lái)的流程就是Activity的生命周期了,
        //本文之前已經(jīng)提到芍耘,其生命周期的各種狀態(tài)的切換由ApplicationThread內(nèi)部來(lái)完成
        mInstrumentation.callActivityOnCreate(activity, r.state);
        if (!activity.mCalled) {
            throw new SuperNotCalledException(
                "Activity " + r.intent.getComponent().toShortString() +
                " did not call through to super.onCreate()");
        }
        r.activity = activity;
        r.stopped = true;
        if (!r.activity.mFinished) {
            activity.performStart();
            r.stopped = false;
        }
        if (!r.activity.mFinished) {
            if (r.state != null) {
                mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
            }
        }
        if (!r.activity.mFinished) {
            activity.mCalled = false;
            mInstrumentation.callActivityOnPostCreate(activity, r.state);
            if (!activity.mCalled) {
                throw new SuperNotCalledException(
                    "Activity " + r.intent.getComponent().toShortString() +
                    " did not call through to super.onPostCreate()");
            }
        }
    }
    r.paused = true;

    mActivities.put(r.token, r);

} catch (SuperNotCalledException e) {
    throw e;

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

return activity;

}

這里面看到

Activity activity = null;
try {
java.lang.ClassLoader cl = r.packageInfo.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);
}
}

這個(gè)方法就是通過(guò)mInstrumentation.newActivity 方法址遇,用classLoader創(chuàng)建activity的實(shí)例,這樣就創(chuàng)建了Activity斋竞,再往下看就是創(chuàng)建Application倔约,以及activity attach的回調(diào)方法。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末坝初,一起剝皮案震驚了整個(gè)濱河市浸剩,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌鳄袍,老刑警劉巖绢要,帶你破解...
    沈念sama閱讀 218,036評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異拗小,居然都是意外死亡重罪,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,046評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門十籍,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)蛆封,“玉大人,你說(shuō)我怎么就攤上這事勾栗〔依椋” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,411評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵围俘,是天一觀的道長(zhǎng)砸讳。 經(jīng)常有香客問(wèn)我琢融,道長(zhǎng),這世上最難降的妖魔是什么簿寂? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,622評(píng)論 1 293
  • 正文 為了忘掉前任漾抬,我火速辦了婚禮,結(jié)果婚禮上常遂,老公的妹妹穿的比我還像新娘纳令。我一直安慰自己,他們只是感情好克胳,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,661評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布平绩。 她就那樣靜靜地躺著,像睡著了一般漠另。 火紅的嫁衣襯著肌膚如雪捏雌。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,521評(píng)論 1 304
  • 那天笆搓,我揣著相機(jī)與錄音性湿,去河邊找鬼。 笑死满败,一個(gè)胖子當(dāng)著我的面吹牛肤频,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播葫录,決...
    沈念sama閱讀 40,288評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼着裹,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼领猾!你這毒婦竟也來(lái)了米同?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,200評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤摔竿,失蹤者是張志新(化名)和其女友劉穎面粮,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體继低,經(jīng)...
    沈念sama閱讀 45,644評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡熬苍,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,837評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了袁翁。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片柴底。...
    茶點(diǎn)故事閱讀 39,953評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖粱胜,靈堂內(nèi)的尸體忽然破棺而出柄驻,到底是詐尸還是另有隱情,我是刑警寧澤焙压,帶...
    沈念sama閱讀 35,673評(píng)論 5 346
  • 正文 年R本政府宣布鸿脓,位于F島的核電站抑钟,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏野哭。R本人自食惡果不足惜在塔,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,281評(píng)論 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望拨黔。 院中可真熱鬧蛔溃,春花似錦、人聲如沸篱蝇。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,889評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)态兴。三九已至狠持,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間瞻润,已是汗流浹背喘垂。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,011評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留绍撞,地道東北人正勒。 一個(gè)月前我還...
    沈念sama閱讀 48,119評(píng)論 3 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像傻铣,于是被迫代替她去往敵國(guó)和親章贞。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,901評(píng)論 2 355

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