編輯:關於 Android 程式設計
「Activity 是怎麼被啟動的」是理解 Android 框架的關鍵問題之一。本文透過逐步閱讀原始碼,追蹤從 ActivityThread 建立 Activity、Window 與 DecorView 的關聯,一路到 View 樹真正被 measure、layout、draw 顯示在螢幕上的完整過程。
入口是 android.app.ActivityThread.performLaunchActivity(),以下是省略後的關鍵片段:
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);
StrictMode.incrementExpectedActivityCount(activity.getClass());
r.intent.setExtrasClassLoader(cl);
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 {
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);
}
}
...
}
三個關鍵點:
Instrumentation.newActivity(),依類名以反射方式建立 Activity 物件。activity.attach(),完成各種初始化綁定。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);
// ... 將各參數賦值給 Activity 的成員變數
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;
}
這裡做了幾件事:先建立 mWindow,再為它設定 WindowManager,最後把 WindowManager 存進 Activity 的 mWindowManager 欄位。
要注意的是,mWindow 的宣告型別是 Window,但實際物件是 PhoneWindow,它與 Activity 的內容顯示密切相關。
attach 完成後,onCreate() 自然被呼叫。而 onCreate 中通常呼叫的 setContentView(),並非由 Activity 自行實作:
public void setContentView(View view, ViewGroup.LayoutParams params) {
getWindow().setContentView(view, params);
initActionBar();
}
getWindow() 回傳的就是 attach 中賦值的 mWindow。Window 是一個抽象類別,setContentView() 在這裡沒有具體實作,真正的實作在 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 有兩個與視圖相關的成員:mDecor(DecorView)與 mContentParent(ViewGroup)。前者是整個視窗的根視圖,後者是應用內容的容器。
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,作為整個視窗的根節點。真正複雜的是 generateLayout:
protected ViewGroup generateLayout(DecorView decor) {
// ... 依樣式、主題、版本等設定視圖屬性
int layoutResource; // 用來 inflate 的資源 id
// ... 依 Window 的 feature 選擇合適的版面,賦值給 layoutResource
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;
}
這個方法關鍵地做了五件事:
findViewById(ID_ANDROID_CONTENT) 取得系統預留的內容容器。mContentParent。setContentView() 設定內容,setTitle() 等操作 ActionBar,requestFeature() 則是 ActionBar 相關特性的開關。這些都是 public 方法,正是留給應用開發者呼叫的。mDecor,而 ActionBar 與 contentParent 都是以 findViewById 從 mDecor 中取出的子視圖。回到 setContentView,installDecor 執行完畢後就是 mContentParent.removeAllViews() 與 addView()。
addView 內部先呼叫 requestLayout()——但這個時候它沒有效果。原因是 View.requestLayout() 會把請求往上傳給 mParent,而此時 mDecor 的 mParent 尚未設定(要等到 ViewRootImpl.setView() 才會賦值),請求鏈中斷在半路。
接著 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(decor, l)。
這個 wm 就是 Activity 的 mWindowManager(WindowManagerImpl),其大部分方法是代理給 WindowManagerGlobal:
public void addView(View view, ViewGroup.LayoutParams params,
Display display, Window parentWindow) {
ViewRootImpl root;
View panelParentView = null;
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) {
throw e;
}
}
重點是 new 了一個 ViewRootImpl,然後呼叫它的 setView。
/** We have one child */
public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
synchronized (this) {
if (mView == null) {
mView = view;
// 在加入 window manager 之前先排入第一次 layout,
// 以確保在任何系統事件送達前完成 relayout
requestLayout();
view.assignParent(this);
}
}
}
注意 ViewRootImpl 並不是 View 的子類。它把傳入的 decor 存為 mView,作為整個視圖樹的根節點,並透過 view.assignParent(this) 把自己設為 decor 的 parent。
這一刻起,requestLayout() 終於有效了——因為 mDecor 知道自己的 parent 是誰,請求鏈得以完整傳遞到 ViewRootImpl,後續的 measure、layout、draw 三步才能啟動。
void scheduleTraversals() {
if (!mTraversalScheduled) {
mTraversalScheduled = true;
mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
mChoreographer.postCallback(Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
...
}
}
ViewRootImpl.requestLayout() 先確認是否在主執行緒,接著呼叫 scheduleTraversals()。它會張開一個同步屏障(sync barrier),確保在這次 traversal 完成前,其他同步訊息不會插隊。
被 post 的 Runnable 其 run() 方法會呼叫 doTraversal(),後者再呼叫 performTraversals()。這個方法很長,核心是按序呼叫:
performMeasure():測量,決定每個 View 的寬高。performLayout():配置,決定每個 View 的位置。performDraw():繪製,把內容畫到螢幕上。把整條鏈條串起來看:
ActivityThread.performLaunchActivity → new Activity → attach(建立 PhoneWindow 與 WindowManager)→ onCreate → setContentView → PhoneWindow.installDecor(建立 DecorView 與 mContentParent)→ addView(視圖樹成形,但 requestLayout 無效)→ 回到 handleResumeActivity → onResume → wm.addView → new ViewRootImpl → setView → assignParent → requestLayout 生效 → performTraversals(measure / layout / draw)。
整個過程花了兩天在 grepcode 上讀原始碼,最大的收穫是:只要原始碼看得夠仔細,多數「為什麼畫面會這樣」的疑問都能自己找出答案。至於這些機制與實際開發(例如自訂 View 的繪製時機、requestLayout 為何有時不生效)之間的連結,還需要更多實務經驗的累積。
Android 安全加密系列:數字簽名與數字憑證原理完整梳理
系列文章索引 Android 安全加密:對稱加密 Android 安全加密:非對稱加密 Android 安全加密:消息摘要 Message Digest Android
Mock Server 利器 —— Moco 完全使用指南
Moco 介紹 開發過程中經常會用到一些 HTTP 網路接口,而這部分功能通常由第三方團隊或後端同事開發,在我們開發時無法提供服務,更甚者,要整合的服務在開發時還不存在。
用 HTML 寫 Android 界面:WebView 與 Java 雙向通信實作
目前 Android 開發的分工還不夠細緻,程序員往往得兼顧界面。美工把視圖切圖交付過來,可真要用 layout 一層層拼出還原度高的界面,既費時又容易走樣。 其實還有一
Android ListView 快速上手:三步驟做出簡易列表
ListView 是非常常見的控制項,以垂直列表的形式呈現資料。而完成一個最簡單的 ListView,只需要三個步驟: 1、在版面配置 XML 中加入 ListView