編輯:關於 Android 程式設計
做 Android 開發,跟我們打交道最多的莫過於 Activity,因為我們不斷地與畫面互動。而 Activity 內部所有跟界面有關的操作,其實都是由 Window 一手包辦的。網路上關於 Window 的源碼分析已經很多,這篇不打算大量貼碼逐行解剖,而是用文字把整個機制串起來,讓人讀完能建立起清楚的整體圖像。
想真正搞懂 Window,我認為至少要回答這六個問題:
本文聚焦在應用級 Window,也就是 Activity。
Android 中的 Window 可分為三類:
圍繞 Window 機制的核心角色有四個:ViewManager(介面)、WindowManager(介面)、WindowManagerImpl(實作類)、WindowManagerGlobal(真正幹活的類)。

它們的關係可以這樣記:WindowManagerImpl 實作 WindowManager,但它自己幾乎不做事,所有方法都轉交給 WindowManagerGlobal;而 WindowManagerGlobal 實作了 ViewManager 介面,是新增、移除、更新 View 的真正執行者。
我們平常呼叫的 setContentView(),本質上就是 Window 的 setContentView()。要找 Window 從哪裡來,得先看 Activity 的啟動流程。
Activity 啟動最終會走到 ApplicationThread.scheduleLaunchActivity,方法末尾送出一則訊息交給 Handler H 處理,訊息標記是 LAUNCH_ACTIVITY。H.handleMessage 命中這個分支後會呼叫 handleLaunchActivity,再透過 performLaunchActivity 真正把 Activity 物件創建出來。而 Activity 的實體化,靠的是 Instrumentation 的反射:
java.lang.ClassLoader cl = r.packageInfo.getClassLoader(); activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);
public Activity newActivity(ClassLoader cl, String className, Intent intent)
throws InstantiationException, IllegalAccessException, ClassNotFoundException {
return (Activity) cl.loadClass(className).newInstance();
}
接著透過 LoadedApk.makeApplication 建立 Application,同樣也是走 Instrumentation 反射,最後回呼 onCreate。
但物件有了還不夠,Android 程式需要上下文環境才能運作,所以 performLaunchActivity 還會建立 Context:
if (activity != null) {
Context appContext = createBaseContextForActivity(r, activity);
activity.attach(appContext, this, getInstrumentation(), r.token, r.ident,
app, r.intent, r.activityInfo, title, r.parent, r.embeddedID,
r.lastNonConfigurationInstances, config);
}
createBaseContextForActivity 建立的是 ContextImpl,隨後透過 attach 把它與 Activity 綁定。
到目前為止,程式碼裡完全看不到 Window 的影子,這說明 Window 一定藏在 attach 裡面:
mWindow = PolicyManager.makeNewWindow(this);
mWindow.setCallback(this);
mWindow.setWindowManager(
(WindowManager) context.getSystemService(Context.WINDOW_SERVICE),
mToken, mComponent.flattenToString(),
(info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
mWindowManager = mWindow.getWindowManager();
這幾行是整個環節的樞紐:PolicyManager.makeNewWindow 最終會 new 出一個 PhoneWindow;接著為它設定回呼;再用 setWindowManager 綁上 WindowManager。
那 WindowManager 從哪來?答案是 context.getSystemService(Context.WINDOW_SERVICE)。而這個系統服務早在建立 ContextImpl 時就註冊好了,它的靜態區塊裡有這麼一段:
registerService(WINDOW_SERVICE, new ServiceFetcher() {
Display mDefaultDisplay;
public Object getService(ContextImpl ctx) {
Display display = ctx.mDisplay;
if (display == null) {
if (mDefaultDisplay == null) {
DisplayManager dm = (DisplayManager) ctx.getOuterContext()
.getSystemService(Context.DISPLAY_SERVICE);
mDefaultDisplay = dm.getDisplay(Display.DEFAULT_DISPLAY);
}
display = mDefaultDisplay;
}
return new WindowManagerImpl(display);
}
});
也就是先取到 Display,再用它建出一個 WindowManagerImpl。
有意思的是,setWindowManager 內部又會呼叫 createLocalWindowManager,而它同樣會 new 一個 WindowManagerImpl。我當初在這裡困惑很久,後來才想通:第一次建立的 WindowManagerImpl 只是帶著 Display、尚未與任何具體 Window 關聯;第二次建立的才是真正與這個 PhoneWindow 綁定的那一份。最後再把它賦給 Activity 的成員變數,因為別處也可能會用到。
小結一下建立流程:
attach 把 Activity 與 ContextImpl 綁定,並在其中建立 PhoneWindow、設定回呼。setWindowManager 為 PhoneWindow 綁上 WindowManager,並回存到 Activity 的成員變數。WindowManager 是介面,實作是 WindowManagerImpl,而 WindowManagerImpl 内部所有方法都轉交給 WindowManagerGlobal。所以 addView 真正執行的是 WindowManagerGlobal.addView;移除與更新也一樣都在這裡。
它的內部邏輯可以簡化為:
// 進行參數合法性檢查,不合法則拋出異常 root = new ViewRootImpl(view.getContext(), display); view.setLayoutParams(wparams); mViews.add(view); mRoots.add(root); mParams.add(wparams); root.setView(view, wparams, panelParentView);
換句話說,它做了四件事:
1. 參數檢查。不合法就拋異常。
2. 建立 ViewRootImpl。Window 是個抽象概念,必須依附 View 而存在,而 ViewRootImpl 就是 Window 與 View 之間溝通的中介——View 繪製流程的起點 performTraversals 就在它裡面。建立時有一句關鍵程式碼:
mWindowSession = WindowManagerGlobal.getWindowSession();
它會為我們取得 IWindowSession:
public static IWindowSession getWindowSession() {
synchronized (WindowManagerGlobal.class) {
if (sWindowSession == null) {
try {
InputMethodManager imm = InputMethodManager.getInstance();
IWindowManager windowManager = getWindowManagerService();
sWindowSession = windowManager.openSession(
imm.getClient(), imm.getInputContext());
float animatorScale = windowManager.getAnimationScale(2);
ValueAnimator.setDurationScale(animatorScale);
} catch (RemoteException e) {
Log.e(TAG, "Failed to open window session", e);
}
}
return sWindowSession;
}
}
其中 getWindowManagerService 取得的是 WindowManagerService,方法是標準的 IPC 取服務:
public static IWindowManager getWindowManagerService() {
synchronized (WindowManagerGlobal.class) {
if (sWindowManagerService == null) {
sWindowManagerService = IWindowManager.Stub.asInterface(
ServiceManager.getService("window"));
}
return sWindowManagerService;
}
}
有了 WMS,再用它 openSession 開出一個 Session。這個 Session 就像一條電話線,之後所有的新增、移除、更新都靠它傳話。
3. 三份清單各自歸位。
private final ArrayList<View> mViews = new ArrayList<View>(); private final ArrayList<ViewRootImpl> mRoots = new ArrayList<ViewRootImpl>(); private final ArrayList<WindowManager.LayoutParams> mParams = new ArrayList<WindowManager.LayoutParams>();
分別存放所有 Window 對應的 View、ViewRootImpl 與布局參數。
4. 呼叫 root.setView。裡面先 requestLayout 從 DecorView 開始重繪,再利用剛剛建立的 Session 呼叫 addToDisplay,最終落到 WMS 的 addWindow。至此 View 才真正掛到 Window 上。
新增流程小結:呼叫 WindowManagerImpl 的 addView → 轉交 WindowManagerGlobal → 參數檢查 → 建立 ViewRootImpl 並取得 Session → View、ViewRootImpl、LayoutParams 分別入列 → 呼叫 setView,由 Session 轉交 WMS 的 addWindow 完成實作。
移除的本質一樣是交給 WindowManager 處理,也就是 WindowManagerImpl。它提供了兩個方法:removeView 與 removeViewImmediate,兩者最終都會走到 WindowManagerGlobal 的 removeView,只差一個 boolean 參數。差別在官方註解裡說得很清楚:
/**
* {@link #removeView} 的特殊版本,會在返回之前立即觸發
* View 層級的 onDetachedFromWindow() 等方法。
* 這不適用於一般應用,正確使用需要格外小心。
*/
public void removeViewImmediate(View view);
WindowManagerGlobal 的 removeView 本身不長:
public void removeView(View view, boolean immediate) {
if (view == null) {
throw new IllegalArgumentException("view must not be null");
}
synchronized (mLock) {
int index = findViewLocked(view, true);
View curView = mRoots.get(index).getView();
removeViewLocked(index, immediate);
if (curView == view) {
return;
}
throw new IllegalStateException("Calling with view " + view
+ " but the ViewAncestor is attached to " + curView);
}
}
先透過 findViewLocked 遍歷陣列取得 index,再呼叫 removeViewLocked:
private void removeViewLocked(int index, boolean immediate) {
ViewRootImpl root = mRoots.get(index);
View view = root.getView();
if (view != null) {
InputMethodManager imm = InputMethodManager.getInstance();
if (imm != null) {
imm.windowDismissed(mViews.get(index).getWindowToken());
}
}
boolean deferred = root.die(immediate);
if (view != null) {
view.assignParent(null);
if (deferred) {
mDyingViews.add(view);
}
}
}
關鍵是 root.die(immediate)。裡面會依 immediate 決定是直接呼叫 doDie(),還是丟一則帶 MSG_DIE 標記的訊息給 Handler。前者傳 false(同步移除),後者傳 true(異步移除)。不論走哪條路,最終都會抵達 doDie()。
doDie() 主要做兩件事:
第一,呼叫 dispatchDetachedFromWindow,裡面又見到 Session 的身影——透過 Session 的 remove 建立通道,最終由 WMS 的 removeWindow 執行,與新增時完全對稱。
第二,呼叫 WindowManagerGlobal.doRemoveView,把當初加進去的三份資料各自移出:
void doRemoveView(ViewRootImpl root) {
synchronized (mLock) {
final int index = mRoots.indexOf(root);
if (index >= 0) {
mRoots.remove(index);
mParams.remove(index);
final View view = mViews.remove(index);
mDyingViews.remove(view);
}
}
}
移除流程小結:呼叫 removeView / removeViewImmediate(後者慎用)→ WindowManagerGlobal 找到 index 並取得對應的 ViewRootImpl → 交給 ViewRootImpl 的 die / doDie 處理 → 透過 Session 轉交 WMS 的 removeWindow 完成跨進程移除 → 最後別忘了把 mViews、mRoots、mParams 三份清單同步清乾淨。
更新最終走到 WindowManagerGlobal.updateViewLayout:
public void updateViewLayout(View view, ViewGroup.LayoutParams params) {
if (view == null) {
throw new IllegalArgumentException("view must not be null");
}
if (!(params instanceof WindowManager.LayoutParams)) {
throw new IllegalArgumentException("Params must be WindowManager.LayoutParams");
}
final WindowManager.LayoutParams wparams = (WindowManager.LayoutParams) params;
view.setLayoutParams(wparams);
synchronized (mLock) {
int index = findViewLocked(view, true);
ViewRootImpl root = mRoots.get(index);
mParams.remove(index);
mParams.add(index, wparams);
root.setLayoutParams(wparams, false);
}
}
想想我們什麼時候需要更新 Window?就是 Window 中某個 View 的 LayoutParams 變了的時候。若由我們自己實作,大概也會先把新屬性套回 View,再觸發重繪——源碼正是如此,只是多包了一層封裝。
先把新 LayoutParams 套回 View,用 index 找到對應的 ViewRootImpl,更新 mParams 清單(移除舊的、放進新的),最後呼叫 root.setLayoutParams。這裡又見到 ViewRootImpl 這個中介。它內部會呼叫 scheduleTraversals,開啟從 DecorView 起的重繪流程;接著 performTraversals 裡呼叫 relayoutWindow,其中再呼叫 Session 的 relayout,最後由 WMS 的 relayoutWindow 落實。
更新流程小結:呼叫 updateViewLayout → 更新 View 的 LayoutParams → 依 index 找到 ViewRootImpl 並同步 mParams → 由 ViewRootImpl 觸發 scheduleTraversals 重繪 View,再透過 Session 轉交 WMS 完成 Window 的重新布局。
把三個流程擺在一起,會發現一條很清楚的主線:WindowManagerImpl 只是外殼,WindowManagerGlobal 才是大腦,ViewRootImpl 是 Window 與 View 之間的橋梁,Session 是通往 WMS 的電話線,而 WMS 是最後的決策者。
釐清 Window、ViewRootImpl、View、WindowManagerImpl、WindowManagerGlobal、Session、WindowManagerService 之間的關係,整個機制其實並不難理解。
本文分析的是 Activity 這個應用級 Window。Dialog 與 Toast 的流程大體類似,只是建立方式與 Window 類型不同,有興趣可以再往下追。文章難免有疏漏之處,歡迎指正。
Java 4 Android 開發教程(一):JDK 安裝與環境變數設定
開發 Android 的第一步是把 Java 開發環境架起來。以下以 Windows 為例,說明 JDK 的安裝與 path、classpath 的設定流程。 一、下載
深入排查:Android 应用被强杀或回收引发空指针崩溃的根治方案
一、问题是如何发生的,又会在什么情况下发生? 当使用者动用手机清理助手,或后台回收机制将我们的应用进程杀死时,就有可能冒出这类空指针问题。下面不妨借一个例子,一同看看这种
Android 圖像資源入門(一):普通圖片、Bitmap 與圖層資源
以前看別人的專案時,發現 drawable 資料夾裡竟然放著 XML 檔。第一次見到這種「XML 圖像資源」時,我實在搞不懂它是幹什麼的。後來抽空研究了一下,才發現這類資
Android進階教學:Splash啟動頁的版本更新業務邏輯
本單元聚焦於Android進階開發中常見的Splash(啟動引導頁)設計,重點在於梳理啟動頁在「版本更新」情境下的業務判斷流程:應用啟動時,Splash頁會先確認目前的版