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)幔嫂。