一.前言
Activity是Android四大組件之一,其內(nèi)部工作過程系統(tǒng)已經(jīng)做了很多封裝膊存,因此宫峦,使得我們啟動一個Activity相當簡單,本篇文章基于android 7.1的源碼將從startActivity這樣簡單操作就可啟動一個Activity昵仅,分析startActivity源碼內(nèi)部的啟動流程。廢話少說累魔,直接給出啟動主流程的時序圖:
二 .啟動流程分析
以不同的方式啟動Activity會經(jīng)歷不同的進程摔笤,而不同進程間是通過Binder方式來通信,常見的啟動Activity主要有兩種:
1.桌面(Launcher)打開一個App的Activity:
Launcher進程->system_server進程->Zygote進程->新App的Activity所在進程
2.在app的Activity組件啟動一個新Activity:
App進程->system_server進程->App進程
本文以在app的Activity組件啟動一個新Activity進行分析垦写。
2.1 MainActivity所在的App進程
步驟1.在app中新建一個MainActivity.java 啟動打開另一個Activity:
Intent intent = new Intent(this,SecondActivity);
startActivity(intent);
很簡單吕世,通過上述代碼就能啟動另一個Activity,然后調(diào)用Activity.startActivity梯投。
步驟2.Activity.startActivity
源碼位置:frameworks/base/core/java/android/app/Activity.java
@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);
}
}
方法內(nèi)部通過判斷參數(shù)options是否為null寞冯,但是都是調(diào)用的Activity.startActivityForResult不同的重載方法
步驟3.Activity.startActivityForResult
源碼位置:frameworks/base/core/java/android/app/Activity.java
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);
if (ar != null) {
mMainThread.sendActivityResult(
mToken, mEmbeddedID, requestCode, ar.getResultCode(),
ar.getResultData());
}
if (requestCode >= 0) {
mStartedActivity = true;
}
cancelInputsAndStartExitTransition(options);
if (options != null) {
mParent.startActivityFromChild(this, intent, requestCode, options);
} else {
mParent.startActivityFromChild(this, intent, requestCode);
}
}
}
根據(jù)mParent是否為空執(zhí)行不同的代碼塊渴析,mParent是什么?其實mParent是一個ActivityGroup吮龄,不過在Android3.0的時候就被Fragment所取代俭茧,所以也就不再對其做討論,會執(zhí)行if分支代碼塊漓帚,然后調(diào)用mInstrumentation.execStartActivity方法母债,mInstrumentation的類型是Intrumentation,接著打開Intrumentation類
步驟4.Intrumentation.execStartActivity
源碼位置:frameworks/base/core/java/android/app/Instrumentation.java
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
...
try {
intent.migrateExtraStreamToClipData();
intent.prepareToLeaveProcess(who);
int result = ActivityManagerNative.getDefault()
.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;
}
發(fā)現(xiàn)在這個方法中調(diào)用ActivityManagerNative.getDefault().startActivity方法尝抖,那么ActivityManagerNative.getDefault()返回什么毡们?其實返回ActivityManagerService的遠程接口,即ActivityManagerProxy接口昧辽,下面看看ActivityManagerNative.getDefault()的源碼衙熔。
打開ActivityManagerNative類看方法getDefault():
static public IActivityManager getDefault() {
return gDefault.get();
}
方法返回gDefault.get()。繼續(xù)看gDefault源碼:
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;
}
};
gDefault是一個單例對象搅荞,其內(nèi)部通過asInterface()方法創(chuàng)建红氯,其中create()方法中
IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE)
獲取一個關(guān)聯(lián)了系統(tǒng)服務(wù)ActivityManagerService的Binder對象,然后把IBinder 的對象b傳給asInterface(b)返回一個IActivityManager的代理對象咕痛,繼續(xù)看asInterface方法的實現(xiàn)痢甘,
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);
}
asInterface()方法返回ActivityManagerProxy對象,因此ActivityManagerNative.getDefault()返回ActivityManagerProxy對象茉贡,然后繼續(xù)時序圖中的ActivityManagerProxy.startActivity塞栅。
步驟5.ActivityManagerProxy.startActivity
源碼位置:frameworks/base/core/java/android/app/ActivityManagerNative.java的內(nèi)部類$ActivityManagerProxy
public int startActivity(IApplicationThread caller, String callingPackage, Intent intent,
String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle options) throws RemoteException {
Parcel data = Parcel.obtain();
Parcel reply = Parcel.obtain();
data.writeInterfaceToken(IActivityManager.descriptor);
data.writeStrongBinder(caller != null ? caller.asBinder() : null);
data.writeString(callingPackage);
intent.writeToParcel(data, 0);
data.writeString(resolvedType);
data.writeStrongBinder(resultTo);
data.writeString(resultWho);
data.writeInt(requestCode);
data.writeInt(startFlags);
if (profilerInfo != null) {
data.writeInt(1);
profilerInfo.writeToParcel(data, Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
} else {
data.writeInt(0);
}
if (options != null) {
data.writeInt(1);
options.writeToParcel(data, 0);
} else {
data.writeInt(0);
}
mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0);
reply.readException();
int result = reply.readInt();
reply.recycle();
data.recycle();
return result;
}
由步驟4可知ActivityManagerProxy是ActivityManagerService的Binder代理類穆端,它會使系統(tǒng)服務(wù)ActivityManagerService的startActivity方法被調(diào)用堵腹。因此咖为,啟動Activity的操作就交給了系統(tǒng)服務(wù)ActivityManagerService來處理毛好。
2.2 把啟動Activity的操作交給ActivityManagerService處理的system_server進程
步驟6.ActivityManagerService.startActivity
源碼位置:
/frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
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());
}
步驟7.ActivityManagerService.startActivityAsUser
源碼位置:
/frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
@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);
}
方法返回mActivityStarter.startActivityMayWait的調(diào)用結(jié)果,mActivityStarter在ActivityManagerService的構(gòu)造函數(shù)進行賦值:
mActivityStarter = new ActivityStarter(this, mStackSupervisor);
mActivityStarter是一個ActivityStarter對象断楷,接著看ActivityStarter.startActivityMayWait的調(diào)用
步驟8.ActivityStarter.startActivityMayWait
源碼位置:
/frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java
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, IActivityManager.WaitResult outResult, Configuration config,
Bundle bOptions, boolean ignoreTargetSecurity, int userId,
IActivityContainer iContainer, TaskRecord inTask) {
...
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);
...
}
startActivityMayWait方法內(nèi)部又調(diào)用了startActivityLocked
步驟9.ActivityStarter.startActivityLocked
源碼位置:
/frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java
final 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) {
...
try {
mService.mWindowManager.deferSurfaceLayout();
err = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
true, options, inTask);
} finally {
mService.mWindowManager.continueSurfaceLayout();
}
postStartActivityUncheckedProcessing(r, err, stack.mStackId, mSourceRecord, mTargetStack);
return err;
}
方法中執(zhí)行了啟動Activity的一些邏輯判斷梅誓,在經(jīng)過判斷邏輯之后調(diào)用startActivityUnchecked方法
步驟10.ActivityStarter.startActivityUnchecked
源碼位置:
/frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask) {
...
mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,
mOptions);
...
}
變量mSupervisor是一個ActivityStackSupervisor對象沽讹。此時啟動過程轉(zhuǎn)移到了ActivityStackSupervisor類的resumeFocusedStackTopActivityLocked方法科汗。
步驟11.ActivityStackSupervisor.resumeFocusedStackTopActivityLocked
源碼位置:
/frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java
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);
}
return false;
}
mFocusedStack是ActivityStack對象,
步驟12.ActivityStack.resumeTopActivityUncheckedLocked
源碼位置:
/frameworks/base/services/core/java/com/android/server/am/ActivityStack.java
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;
if (mService.mLockScreenShown == ActivityManagerService.LOCK_SCREEN_LEAVING) {
mService.mLockScreenShown = ActivityManagerService.LOCK_SCREEN_HIDDEN;
mService.updateSleepIfNeededLocked();
}
result = resumeTopActivityInnerLocked(prev, options);
} finally {
mStackSupervisor.inResumeTopActivity = false;
}
return result;
}
步驟13.ActivityStack.resumeTopActivityInnerLocked
源碼位置:
/frameworks/base/services/core/java/com/android/server/am/ActivityStack.java
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
...
mStackSupervisor.startSpecificActivityLocked(next, true, true);
...
}
該方法內(nèi)部邏輯比較復(fù)雜绷雏,比如暫停啟動Activity的那個Activity等操作头滔,接著又會調(diào)用ActivityStackSupervisor中的startSpecificActivityLocked函數(shù)
步驟14.ActivityStackSupervisor.startSpecificActivityLocked
源碼位置:
/frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java
void startSpecificActivityLocked(ActivityRecord r,
boolean andResume, boolean checkConfig) {
ProcessRecord app = mService.getProcessRecordLocked(r.processName,
r.info.applicationInfo.uid, true);
r.task.stack.setLaunchTime(r);
if (app != null && app.thread != null) {
try {
if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
|| !"android".equals(r.info.packageName)) {
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.
}
mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
"activity", r.intent.getComponent(), false, false, true);
}
方法會判斷Activity的application是否已經(jīng)啟動,本文是application已啟動的Activity啟動另一個Activity涎显,所以會調(diào)用realStartActivityLocked坤检,如果通過Launcher組件啟動Activity,此時該Activity的application未啟動期吓,會mService.startProcessLocked去創(chuàng)建早歇。
步驟15.ActivityStackSupervisor.realStartActivityLocked
源碼位置:
/frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java
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, new Configuration(mService.mConfiguration),
new Configuration(task.mOverrideConfig), r.compat, r.launchedFromPackage,
task.voiceInteractor, app.repProcState, r.icicle, r.persistentState, results,
newIntents, !andResume, mService.isNextTransitionForward(), profilerInfo);
...
}
app是一個ProcessRecord對象,打開ProcessRecord類看下app.thread是什么
final class ProcessRecord {
IApplicationThread thread;
}
app.thread的類型是IApplicationThread,而IApplicationThread是一個接口箭跳,IApplicationThread是一個接口晨另,其實現(xiàn)初始化是ActivityManagerNative中的onTransact中:
@Override
public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
throws RemoteException {
switch (code) {
case START_ACTIVITY_TRANSACTION:
{
data.enforceInterface(IActivityManager.descriptor);
IBinder b = data.readStrongBinder();
IApplicationThread app = ApplicationThreadNative.asInterface(b);
...
}
...
}
static public IApplicationThread asInterface(IBinder obj) {
if (obj == null) {
return null;
}
IApplicationThread in =
(IApplicationThread)obj.queryLocalInterface(descriptor);
if (in != null) {
return in;
}
return new ApplicationThreadProxy(obj);
}
接著看ApplicationThreadProxy.scheduleLaunchActivity源碼:
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) throws RemoteException {
Parcel data = Parcel.obtain();
data.writeInterfaceToken(IApplicationThread.descriptor);
intent.writeToParcel(data, 0);
data.writeStrongBinder(token);
data.writeInt(ident);
info.writeToParcel(data, 0);
curConfig.writeToParcel(data, 0);
if (overrideConfig != null) {
data.writeInt(1);
overrideConfig.writeToParcel(data, 0);
} else {
data.writeInt(0);
}
compatInfo.writeToParcel(data, 0);
data.writeString(referrer);
data.writeStrongBinder(voiceInteractor != null ? voiceInteractor.asBinder() : null);
data.writeInt(procState);
data.writeBundle(state);
data.writePersistableBundle(persistentState);
data.writeTypedList(pendingResults);
data.writeTypedList(pendingNewIntents);
data.writeInt(notResumed ? 1 : 0);
data.writeInt(isForward ? 1 : 0);
if (profilerInfo != null) {
data.writeInt(1);
profilerInfo.writeToParcel(data, Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
} else {
data.writeInt(0);
}
mRemote.transact(SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION, data, null,
IBinder.FLAG_ONEWAY);
data.recycle();
}
ApplicationThreadProxy.scheduleLaunchActivity()將傳遞過來的參數(shù)寫入Parcel對象中,通過ApplicationThreadProxy內(nèi)部的Binder對象mRemote發(fā)起一個 類型為SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION的進程間通信請求谱姓。
ApplicationThreadProxy是ActivityThread$ApplicationThread的代理類借尿,真正執(zhí)行的是ActivityThread$ApplicationThread中的scheduleLaunchActivity,所以我們看一下ActivityThread$ApplicationThread中的scheduleLaunchActivity的實現(xiàn)
2.3 system_server進程接著把啟動Activity的操作又交回給app進程
步驟16.ActivityThread$ApplicationThread.scheduleLaunchActivity
源碼位置:
/frameworks/base/core/java/android/app/ActivityThread.java的內(nèi)部類ApplicationThread
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);
}
步驟17.ActivityThread.sendMessage
源碼位置:
/frameworks/base/core/java/android/app/ActivityThread.java
private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
if (DEBUG_MESSAGES) Slog.v(
TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
+ ": " + arg1 + " / " + obj);
Message msg = Message.obtain();
msg.what = what;
msg.obj = obj;
msg.arg1 = arg1;
msg.arg2 = arg2;
if (async) {
msg.setAsynchronous(true);
}
mH.sendMessage(msg);
}
mH是一個H對象屉来,類H是ActivityThread的內(nèi)部類路翻,并繼承了Handler。接著在handleMessage方法中看LAUNCH_ACTIVITY類型消息的處理
步驟18.ActivityThread$H.handleMessagehandleMessage
源碼位置:
/frameworks/base/core/java/android/app/ActivityThread.java內(nèi)部類H
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;
...
}
啟動過程又調(diào)用ActivityThread.handleLaunchActivity方法來實現(xiàn)
步驟19.ActivityThread.handleLaunchActivity
源碼位置:
/frameworks/base/core/java/android/app/ActivityThread.java
private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
...
Activity a = performLaunchActivity(r, customIntent);
...
}
從源碼可知茄靠,執(zhí)行performLaunchActivity方法完成Activity對象的創(chuàng)建和啟動茂契。
步驟20.ActivityThread.performLaunchActivity
源碼位置:/frameworks/base/core/java/android/app/ActivityThread.java
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
ActivityInfo aInfo = r.activityInfo;
if (r.packageInfo == null) {
r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
Context.CONTEXT_INCLUDE_CODE);
}
//1.獲取啟動的Activity的ComponentName對象,里面包含了包名慨绳,類名相關(guān)的信息
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 {
//2.創(chuàng)建Activity的實例掉冶,使用類加載器創(chuàng)建Activity對象,調(diào)用Instrumentation.newActivity方法儡蔓,
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);
}
}
try {
//3.創(chuàng)建Application對象郭蕉;
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
if (activity != null) {
//4.創(chuàng)建Activity的上下文環(huán)境,即創(chuàng)建了ContextImpl對象喂江;
Context appContext = createBaseContextForActivity(r, activity);
CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Configuration config = new Configuration(mCompatConfiguration);
if (r.overrideConfig != null) {
config.updateFrom(r.overrideConfig);
}
if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
+ r.activityInfo.name + " with config " + config);
Window window = null;
if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
window = r.mPendingRemoveWindow;
r.mPendingRemoveWindow = null;
r.mPendingRemoveWindowManager = null;
}
//5.調(diào)用Activity.attach方法召锈,初始化Activity類里的一些數(shù)據(jù)
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);
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;
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
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.isPersistable()) {
if (r.state != null || r.persistentState != null) {
mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
r.persistentState);
}
} else if (r.state != null) {
mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
}
}
if (!r.activity.mFinished) {
activity.mCalled = false;
//6.調(diào)用Instrumentation.callActivityOnCreate方法
if (r.isPersistable()) {
mInstrumentation.callActivityOnPostCreate(activity, r.state,
r.persistentState);
} else {
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;
}
從源碼上看,performLaunchActivity方法執(zhí)行一些對象的創(chuàng)建获询,最后在代碼中調(diào)用Instrumentation的callActivityOnCreate方法
步驟21.Instrumentation.callActivityOnCreate
源碼位置:/frameworks/base/core/java/android/app/Instrumentation.java
public void callActivityOnCreate(Activity activity, Bundle icicle) {
prePerformCreate(activity);
activity.performCreate(icicle);
postPerformCreate(activity);
}
接著執(zhí)行activity的performCreate方法
步驟22.Activity.performCreate
源碼位置:/frameworks/base/core/java/android/app/Activity.java
final void performCreate(Bundle icicle) {
restoreHasCurrentPermissionRequest(icicle);
onCreate(icicle);
mActivityTransitionState.readState(icicle);
performCreateCommon();
}
步驟23.Activity.onCreate
源碼位置:/frameworks/base/core/java/android/app/Activity.java
終于找到期待已久的Activity生命周期中onCreate方法的調(diào)用涨岁。
本文重點是對Activity的啟動的主流程進行分析,并未對源碼中有很多細節(jié)(包括啟動模式吉嚣、任務(wù)棧等)進行分析梢薪。