開(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ì)象
對(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 類的功能
接下來(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)方法。