編輯:Android 資訊
本文透過 DDMS 對一個簡單 Demo 做除錯標記,暫停主執行緒後觀察呼叫堆疊,逐層拆解 Activity 從被啟動到畫面真正呈現的完整路徑。

應用程式進入點位於 android.app.ActivityThread 的 main()。這裡會初始化一個 Looper 形成訊息迴圈,之後主執行緒的所有工作都會被投遞到與該 Looper 綁定的 Handler 中處理。
這個 Handler 是 ActivityThread 的內部類 H,繼承自 Handler。觀察它的 handleMessage(),可以看到 what 值為 LAUNCH_ACTIVITY 的分支呼叫了 handleLaunchActivity()。


該方法主要執行 performLaunchActivity() 與 handleResumeActivity() 兩個步驟。
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
...
Activity activity = null;
try {
java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);
...
} catch (Exception e) { ... }
try {
...
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);
activity.mCalled = false;
mInstrumentation.callActivityOnCreate(activity, r.state);
...
}
}
...
}三個重點:以類名反射建立 Activity 物件;呼叫 attach() 完成上下文綁定;最後由 Instrumentation 代為呼叫 onCreate()。事實上 Activity 所有生命週期方法都是由 Instrumentation 觸發的。
final void attach(Context context, ActivityThread aThread, Instrumentation instr,
IBinder token, int ident, Application application, Intent intent,
ActivityInfo info, CharSequence title, Activity parent, String id,
NonConfigurationInstances lastNonConfigurationInstances, Configuration config) {
attachBaseContext(context);
mFragments.attachActivity(this, mContainer, null);
mWindow = PolicyManager.makeNewWindow(this);
...
mWindow.setWindowManager(
(WindowManager) context.getSystemService(Context.WINDOW_SERVICE),
mToken, mComponent.flattenToString(),
(info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
if (mParent != null) {
mWindow.setContainer(mParent.getWindow());
}
mWindowManager = mWindow.getWindowManager();
mCurrentConfig = config;
}attach() 主要完成三件事:為 mWindow 賦值、替 mWindow 掛上 WindowManager、再把取得的管理者回寫給 Activity 的 mWindowManager。mWindow 宣告型別是 Window,實際物件則是 PhoneWindow,負責與畫面內容呈現相關的一切。

public void setContentView(View view, ViewGroup.LayoutParams params) {
getWindow().setContentView(view, params);
initActionBar();
}Activity 本身並未實作這個方法,而是轉交給 getWindow() 回傳的 Window 物件。Window 是抽象類,真正的實作在 com.android.internal.policy.impl.PhoneWindow。
@Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
if (mContentParent == null) {
installDecor();
} else {
mContentParent.removeAllViews();
}
mContentParent.addView(view, params);
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
cb.onContentChanged();
}
}PhoneWindow 中有兩個與視圖相關的成員:DecorView 型別的 mDecor,以及 ViewGroup 型別的 mContentParent。

private void installDecor() {
if (mDecor == null) {
mDecor = generateDecor();
...
}
if (mContentParent == null) {
mContentParent = generateLayout(mDecor);
...
}
}
protected DecorView generateDecor() {
return new DecorView(getContext(), -1);
}DecorView 是 PhoneWindow 的內部類,繼承自 FrameLayout,作為整個視窗的根視圖。
protected ViewGroup generateLayout(DecorView decor) {
// 依主題、樣式、版本設定各項屬性
int layoutResource;
// 依 Window feature 挑選對應的版面資源 id
mDecor.startChanging();
View in = mLayoutInflater.inflate(layoutResource, null);
decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
ViewGroup contentParent = (ViewGroup) findViewById(ID_ANDROID_CONTENT);
if (contentParent == null) {
throw new RuntimeException("Window couldn't find content container view");
}
// 設定背景、ActionBar 屬性
mDecor.finishChanging();
return contentParent;
}這段方法關鍵作為有四點:依 FLAG 決定 LayoutParams;依 FEATURE 選出合適的版面資源 id;把該資源 inflate 成 View 後塞進 DecorView;最後以 findViewById(ID_ANDROID_CONTENT) 取出內容容器並回傳給 mContentParent。
行文至此可以歸納出幾個結論:Activity 與 PhoneWindow 是一對一關係;PhoneWindow 管理整個頁面內容(不含最頂端系統狀態列),同時統籌 ActionBar 與內容區;setContentView() 負責內容主體,setTitle()、requestFeature() 等則操作 ActionBar 相關屬性;PhoneWindow 本身不是 View,真正的視圖是 mDecor,ActionBar 與 contentParent 都是從 mDecor 中查找出來的。
回到 setContentView():installDecor() 結束後先執行 mContentParent.removeAllViews() 清空舊內容(這也解釋了連續呼叫兩次不會殘留),再透過 addView() 掛上新版面。

addView() 一開始呼叫的 requestLayout() 在此階段其實不生效——視圖尚未掛上真正的 Root,mParent 還是空的。真正起作用的是後續 addViewInner():把 child 存進自己的 View 陣列,並將 child 的 parent 指向自己。此時畫面依舊空白,只是 mDecor → mContentParent → 使用者版面 的樹狀結構已經搭好。
final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward,
boolean reallyResume) {
...
ActivityClientRecord r = performResumeActivity(token, clearHide);
if (r != null) {
final Activity a = r.activity;
...
if (r.window == null && !a.mFinished && willBeVisible) {
r.window = r.activity.getWindow();
View decor = r.window.getDecorView();
decor.setVisibility(View.INVISIBLE);
ViewManager wm = a.getWindowManager();
WindowManager.LayoutParams l = r.window.getAttributes();
a.mDecor = decor;
l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
l.softInputMode |= forwardBit;
if (a.mVisibleFromClient) {
a.mWindowAdded = true;
wm.addView(decor, l);
}
}
}
}performResumeActivity() 透過 Instrumentation 觸發 onResume()。而 wm.addView() 是畫面出現的臨門一腳——wm 來自 Activity 的 mWindowManager,其 addView() 內部會建立 ViewRootImpl 並呼叫它的 setView()。
public void addView(View view, ViewGroup.LayoutParams params, Display display, Window parentWindow) {
...
root = new ViewRootImpl(view.getContext(), display);
view.setLayoutParams(wparams);
mViews.add(view);
mRoots.add(root);
mParams.add(wparams);
...
try {
root.setView(view, wparams, panelParentView);
} catch (RuntimeException e) { ... }
}public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
synchronized (this) {
if (mView == null) {
mView = view;
// Schedule the first layout -before- adding to the window manager
requestLayout();
...
view.assignParent(this);
}
}
}ViewRootImpl 並不是 View 的子類,它扮演的是整棵視圖樹的根節點角色。setView() 裡先記錄 mView、呼叫 requestLayout(),最後把 view 的 parent 註冊為自己。直到這一刻 mDecor 才終於知道自己的父節點是誰,requestLayout() 也才真正具備意義,後續的 measure、layout、draw 三步才能啟動。

requestLayout() 會先確認目前是否在主執行緒,接著呼叫 scheduleTraversals(),顧名思義就是安排一次從根節點開始的樹狀遍歷。

被標記的 Runnable 在 run() 中呼叫 doTraversal(),後者再進入 performTraversals()。這個方法相當長,依序觸發 performMeasure()、performLayout()、performDraw(),也就是控制項層級的測量、配置與繪製。這部分的細節留待下一篇再談。
花兩天時間在原始碼裡來回摸索,收穫確實不小。最大的體會是:只要原始碼足夠完整,耐心讀下去总能拼出全貌。至於這些機制與日常開發實務該如何互相印證,還需要更多經驗累積。
Android UI 元件系列:Dialog 對話方塊實作
對話方塊是 Android 中不可或缺的元件。使用時通常需要借助 AlertDialog.Builder 類別;除了系統預設樣式外,我們也能自訂對話方塊。若對話方塊設定了
Android UI 元件系列:WebView 網路檢視
Android 的網路功能十分強大,WebView 元件能直接載入網頁,可將其視為一個內建的瀏覽器。要實現這個功能,具體步驟如下: 1、在版面配置檔中宣告 WebView
Android UI 元件系列:TabWidget 切換卡
Tab 選項卡的樣式類似於電話簿的介面,透過多個標籤切換不同的內容。要實現這個效果,首先必須了解 TabHost——它是一個用來容納多個 Tab 標籤的容器,每個 Tab
Android 性能優化:盤點常見的內存洩漏場景
前言 內存洩漏,相信每個開發者在實戰中都遇過,只是它並不「眼見為實」——因為它發生在堆裡。要檢測程式中是否存在內存洩漏,通常可借助 LeakCanary、MAT 等工具。