編輯:關於 Android 程式設計
我們每天寫 startActivity(),但這個方法背後到底走了哪些路徑?這篇順著源碼把一條啟動鏈路串起來。
兩者透過 Binder 與 Handler 訊息機制協作:AMS 決定要啟動哪個 Activity,然後把啟動訊息發給目標進程的 ActivityThread。
public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
ActivityInfo info, Bundle state, List<ResultInfo> pendingResults,
List<Intent> pendingNewIntents, boolean notResumed, boolean isForward) {
ActivityClientRecord r = new ActivityClientRecord();
r.token = token;
r.ident = ident;
r.intent = intent;
r.activityInfo = info;
r.state = state;
r.pendingResults = pendingResults;
r.pendingIntents = pendingNewIntents;
r.startsNotResumed = notResumed;
r.isForward = isForward;
queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
}
注意它把啟動所需的所有資訊打包進 ActivityClientRecord,再交給 queueOrSendMessage 排入主線程的 MessageQueue——這一步只是排隊,真正的動作在主線程空閒時才會發生。
public void handleMessage(Message msg) {
switch (msg.what) {
case LAUNCH_ACTIVITY: {
ActivityClientRecord r = (ActivityClientRecord) msg.obj;
r.packageInfo = getPackageInfoNoCheck(r.activityInfo.applicationInfo);
handleLaunchActivity(r, null);
}
break;
// ... 其他訊息類型
}
}
private final void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
unscheduleGcIdler(); // 即將回到前台,取消背景 GC
Activity a = performLaunchActivity(r, customIntent); // 核心:真正建立 Activity
if (a != null) {
r.createdConfig = new Configuration(mConfiguration);
Bundle oldState = r.state;
handleResumeActivity(r.token, false, r.isForward);
if (!r.activity.mFinished && r.startsNotResumed) {
// AMS 要求這個 Activity 啟動後先停在 paused 狀態(可見但不在前台)
// 做法是先走一次完整啟動流程,再補一次 onPause
r.activity.mCalled = false;
mInstrumentation.callActivityOnPause(r.activity);
r.state = oldState; // 保留原始 state,以備重建時使用
if (!r.activity.mCalled) {
throw new SuperNotCalledException(
"Activity " + r.intent.getComponent().toShortString()
+ " did not call through to super.onPause()");
}
r.paused = true;
}
} else {
// 啟動失敗,通知 AMS 取消
try {
ActivityManagerNative.getDefault()
.finishActivity(r.token, Activity.RESULT_CANCELED, null);
} catch (RemoteException ex) { }
}
}
這個方法很長,但骨架就是「反射 new 出物件 → attach 環境 → 依序回呼生命週期方法」。
private final Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
ActivityInfo aInfo = r.activityInfo;
if (r.packageInfo == null) {
r.packageInfo = getPackageInfo(aInfo.applicationInfo, Context.CONTEXT_INCLUDE_CODE);
}
ComponentName component = r.intent.getComponent();
if (component == null) {
component = r.intent.resolveActivity(mInitialApplication.getPackageManager());
r.intent.setComponent(component);
}
// 處理 alias 情況
if (r.activityInfo.targetActivity != null) {
component = new ComponentName(r.activityInfo.packageName, r.activityInfo.targetActivity);
}
Activity activity = null;
try {
// 1. 用 ClassLoader 反射建立 Activity 實例
ClassLoader cl = r.packageInfo.getClassLoader();
activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);
r.intent.setExtrasClassLoader(cl);
if (r.state != null) {
r.state.setClassLoader(cl);
}
} catch (Exception e) {
throw new RuntimeException("Unable to instantiate activity " + component, e);
}
try {
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
if (activity != null) {
// 2. 建立 Context 並綁定
ContextImpl appContext = new ContextImpl();
appContext.init(r.packageInfo, r.token, this);
appContext.setOuterContext(activity);
CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Configuration config = new Configuration(mConfiguration);
// 3. attach:把 Context、ActivityThread、 Instrumentation、token 等塞進 Activity
activity.attach(appContext, this, getInstrumentation(), r.token, r.ident,
app, r.intent, r.activityInfo, title, r.parent, r.embeddedID,
r.lastNonConfigurationInstance,
r.lastNonConfigurationChildInstances, config);
int theme = r.activityInfo.getThemeResource();
if (theme != 0) {
activity.setTheme(theme);
}
// 4. 依序回呼生命週期
activity.mCalled = false;
mInstrumentation.callActivityOnCreate(activity, r.state); // onCreate
if (!activity.mCalled) {
throw new SuperNotCalledException("Activity " + ... + " did not call through to super.onCreate()");
}
r.activity = activity;
r.stopped = true;
if (!r.activity.mFinished) {
activity.performStart(); // onStart
r.stopped = false;
}
if (!r.activity.mFinished && r.state != null) {
mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
}
if (!r.activity.mFinished) {
activity.mCalled = false;
mInstrumentation.callActivityOnPostCreate(activity, r.state); // onPostCreate
if (!activity.mCalled) {
throw new SuperNotCalledException("Activity " + ... + " did not call through to super.onPostCreate()");
}
}
}
r.paused = true;
mActivities.put(r.token, r); // 以 token 為 key 記錄,供後續調度使用
} catch (Exception e) {
throw new RuntimeException("Unable to start activity " + component, e);
}
return activity;
}
ContextImpl、ActivityThread、Instrumentation、token 等一整套執行環境綁到 Activity 身上。所以在 onCreate 之前,Activity 就已經能用 getSystemService() 了。callActivityOnCreate 等)都經由它轉一手,這也是單元測試能攔截生命週期的原因。activity.mCalled。若你在 onCreate 忘了呼叫 super.onCreate(),就是從這裡拋出來的。onStart 之後、onPostCreate 之前執行,這是 Activity 重建時恢復狀態的位置。mActivities.put(r.token, r) 之後,AMS 要 pause/stop/destroy 哪個 Activity,都是靠 token 找回對應的 record。整條鏈路濃縮成一句話:AMS 決定 → 訊息進 ActivityThread 的 MessageQueue → 主線程取出 → 反射建立物件 → attach 環境 → 依序回呼 onCreate/onStart/onRestoreInstanceState → onResume。
仿 QQ 空間相冊橫向滑動展示多圖:MyHorizontalScrollView 實作
動手客製化吧 版面配置檔:activity_main.xml 版面配置檔:activity_index_gallery_item.xml
Android設計模式之單例模式解析
模式意圖單例模式是設計模式中最簡單的一種。它保證一個類只有一個實例,並提供一個全局訪問點。相比全局變量,單例模式更加可控,也能避免命名空間污染。在Android系統中,許
Android JNI 初探:從 Java 呼叫 C 的完整流程
本文用一個小例子帶大家初探 JNI。開始之前,請先確認 NDK 環境已建置完成(可參考《Android NDK 環境建置》)。 一、實作目標 這個範例的功能很單純:在 A
Android 仿今日頭條頻道移動:ListView Item 動畫遷移實作
效果與思路這個範例模擬資訊類應用中常見的頻道管理效果:上方與下方各有一個 ListView,當使用者點擊下方項目時,該項目會以動畫方式移動到上方清單的最後一項,同時下方清