各位看官好,本文是Android Framework之Activity啓動流程的第三篇,本篇將分析Activity生命週期的回調,新世界的大門就在眼前,走起。
第一篇:Android Framework之Activity啓動流程(一)
第二篇:Android Framework之Activity啓動流程(二)
執行完ApplicationThread# handleBindApplication ()之後,這時候新進程已經啓動。
回到AMS# attachApplicationLocked(),代碼邏輯來到了上篇文章的註釋5處,調用了ActivityStackSupervisor# attachApplicationLocked,在裏面又執行了realStartActivityLocked(),這樣就回到了第一篇末尾所說到的第二種情況,接下來分析第二種情況。
我們看下ApplicationThread# scheduleLaunchActivity()
public final void scheduleLaunchActivity(/*參數省略*/){
//……省略代碼
sendMessage(H.LAUNCH_ACTIVITY, r);
}
sendMessage內部使用了Hanlder,發送了一個H.LAUNCH_ACTIVITY類型的消息,然後調用handleLaunchActivity()->performLaunchActivity()方法。
看看這兩個方法到底幹了什麼事。
ActivityThread# handleLaunchActivity()
private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
// 當前進程正活躍,避免GC
unscheduleGcIdler();
//確保使用的是最近的配置
handleConfigurationChanged(null, null);
//在創建Activity之前初始化WindowManagerService
if (!ThreadedRenderer.sRendererDisabled) {
GraphicsEnvironment.earlyInitEGL()
}
WindowManagerGlobal.initialize();
//======== 註釋9 ========
//執行performLaunchActivity(),並返回Activity對象
Activity a = performLaunchActivity(r, customIntent);
if (a != null) {
r.createdConfig = new Configuration(mConfiguration);
reportSizeConfigurations(r);
Bundle oldState = r.state;
//======== 註釋10=========
//啓動成功後,恢復Activity
handleResumeActivity(r.token, false, r.isForward,!r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);
//……省略代碼
}
}
參數列表中的ActivityClientRecord可以看做是一個Activity的實例,同時還包括了其他一些屬性,主要是對Activity狀態進行記錄。
handleLaunchActivity()主要有兩個操作:
1.註釋9:performLaunchActivity()
該方法主要是調用Activity的onCreate(),onStart(),onRestoreInstance(),onPostCreate()生命週期
2.註釋10:handleResumeActivity()
該方法會調用Activity的onResume()生命週期
先來看看ActivityThread# performLaunchActivity()
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
ActivityInfo aInfo = r.activityInfo;
if (r.packageInfo == null) {
//從PackageManagerService獲取應用包信息
r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
Context.CONTEXT_INCLUDE_CODE);
}
ComponentName component = r.intent.getComponent();
if (component == null) {
//獲取組件信息
component = r.intent.resolveActivity(
mInitialApplication.getPackageManager());
r.intent.setComponent(component);
}
//如果提前設置好了目標Activity,則重新設置組件信息
if (r.activityInfo.targetActivity != null) {
component = new ComponentName(r.activityInfo.packageName,
r.activityInfo.targetActivity);
}
ContextImpl appContext = createBaseContextForActivity(r);
Activity activity = null;
try {
//利用ClassLoader去加載Activity
java.lang.ClassLoader cl = appContext.getClassLoader();
//利用Instrumentation創建Activity實例
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) {
//……省略代碼
}
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的onCreate()方法
//這裏回調的重載函數由ActivityInfo的persistableMode參數決定
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
r.activity = activity;
r.stopped = true;
if (!r.activity.mFinished) {
//回調Activity的onStart()方法,同時會改變FragmentManager的狀態信息
// mInstrumentation.callActivityOnStart(this);
activity.performStart();
r.stopped = false;
}
//回調Activity的onRestoreInstanceState()方法
//這裏的回調方法同樣由ActivityInfo的persistableMode參數決定
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);
}
}
//回調Activity的OnPostCreate()方法
if (!r.activity.mFinished) {
activity.mCalled = false;
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){
……
}
return activity;
}
ActivityThread#handleResumeActivity()
final void handleResumeActivity(IBinder token,
boolean clearHide, boolean isForward, boolean reallyResume, int seq, String reason) {
ActivityClientRecord r = mActivities.get(token);
//======== 註釋11=========
//回調Activity的onResume()方法
r = performResumeActivity(token, clearHide, reason);
if (r != null) {
final Activity a = r.activity;
final int forwardBit = isForward ? WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
//顯示window
if (r.window == null && !a.mFinished && willBeVisible) {
……
ViewManager wm = a.getWindowManager();
……
//將decorView添加到WindowManager中
wm.addView(decor, l);
}
……
//更新佈局
wm.updateViewLayout(decor, l);
……
if (reallyResume) {
try {
//通知AMS已經Resume了
ActivityManager.getService().activityResumed(token);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
} else {
try {
//如果在onResume之前拋出異常了,則通知AMS結束該Activity
ActivityManager.getService()
.finishActivity(token, Activity.RESULT_CANCELED, null,
Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
}
}
}
}
該方法主要是回調Activity的onResume()方法(實際上是調用Instrumentation.callActivityOnResume(this)來執行),並將DecorView添加到WindowManager中,這裏的WindowManager是a.getWindowManager()得到的,其實現是WindowManagerImpl,這步操作在onResume()方法之後執行。
至此,Activity的啓動流程分析完畢。
看完之後感覺如何,是否恍然大悟?
總結
1、 startActivity()通過Instrumentation向AMS進程發起startActivity()請求
2、 AMS收到啓動請求後由ActivityStarter處理Flags和Intent信息,然後再由ActivityStackSupervisor和ActivityStack處理Task和Stack流程
3、 在ActivityStackSupervisor中判斷app進程是否存在,若不存在則請求AMS進程創建新進程,app進程存在的情況請直接跳到第7步
4、 AMS進程通過Socket方式請求Zygote fork新進程
5、 在新進程裏創建ActivityThread(主線程)並開啓Looper循環,同時將ApplicationThread綁定到AMS
6、 AMS回調ApplicationThread的bindApplication()方法將自身與新進程綁定,並在ActivityThread的handleBindApplication()方法中創建應用的Application
7、 Application創建成功後,AMS調用ActivityStackSupervisor# realStartActivityLocked向ActivityThread發送創建Activity請求
8、 ActivityThread利用ClassLoader去加載Activity,並回調其生命週期方法。