編輯:關於 Android 開發
Window 是一個抽象類,它的具體實作是 PhoneWindow。想建立一個 Window 其實很簡單,只要取得一個 WindowManager 即可,而 Window 的真正實作位於 WindowManagerService 當中,兩者之間的互動其實就是一次 IPC(跨進程)的過程。
以下是一段使用 WindowManager 的範例:
mFloatingButton = new Button(this); mFloatingButton.setText( "window"); mLayoutParams = new WindowManager.LayoutParams( LayoutParams. WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 0, 0, PixelFormat. TRANSPARENT); mLayoutParams. flags = LayoutParams.FLAG_NOT_TOUCH_MODAL | LayoutParams. FLAG_NOT_FOCUSABLE | LayoutParams. FLAG_SHOW_WHEN_LOCKED; mLayoutParams. type = LayoutParams. TYPE_SYSTEM_ERROR; mLayoutParams. gravity = Gravity. LEFT | Gravity. TOP; mLayoutParams. x = 100; mLayoutParams. y = 300; mFloatingButton.setOnTouchListener( this); mWindowManager.addView( mFloatingButton, mLayoutParams);
其中 flags 與 type 這兩個屬性格外重要。先來看 flags:
FLAG_NOT_TOUCH_MODAL 表示該視窗不需要獲取焦點,也不接收各種輸入事件,最終會直接把事件傳遞給下層具有焦點的視窗。FLAG_NOT_FOCUSABLE 則是讓視窗範圍外的點擊事件傳遞到底層視窗,而範圍內的事件由自己處理,這個屬性通常都必須設定,非常關鍵。而 FLAG_SHOW_WHEN_LOCKED 的作用是讓視窗能顯示在鎖屏介面上。
接著看 type 參數。Window 共有三種類型:應用視窗、子視窗與系統視窗。應用視窗對應一個 Activity;子視窗無法獨立存在,必須依附在父視窗上,例如常用的 Dialog;系統視窗則需要宣告權限才能建立,例如 Toast。Window 帶有 z-ordered 屬性,層級數字越大就越靠近頂層。應用視窗的層級是 1 到 99,子視窗是 1000 到 1999,系統視窗則是 2000 到 2999,這些層級對應的就是 WindowManager 的 type 參數。系統層級常用到的有 TYPE_SYSTEM_OVERLAY 與 TYPE_SYSTEM_ERROR,例如要使用 TYPE_SYSTEM_ERROR,只需設定 mLayoutParams.type = LayoutParams.TYPE_SYSTEM_ERROR,同時在清單中加入
有了對 Window 的基本認識之後,我們再來看看它底層究竟是如何載入 View 的。
其實 Window 的建立過程,和我先前寫過的 LayoutInflater 原始碼分析有些相似。Window 是在 Activity 建立的 attach 方法中,透過 PolicyManager 的 makeNewWindow 方法完成的。由於 Activity 實作了 Window 的 Callback 介面,因此當 Window 狀態改變時就會回呼 Activity 的方法,例如 onAttachedToWindow 等。PolicyManager 真正的實作類是 Policy,程式碼如下:
public Window makeNewWindow(Context context) { return new PhoneWindow(context); }
至此 Window 就建立完成了。接下來分析 View 是如何被附加到 Window 上的,可以從 Activity 的 setContentView 方法看起。
public void setContentView(int layoutResID) { getWindow().setContentView(layoutResID); initWindowDecorActionBar(); }
這個方法主要做兩件事:設定內容與設定 ActionBar。由於 Window 的實作是 PhoneWindow,我們看它的 setContentView:
public void setContentView(int layoutResID) { if (mContentParent == null) { installDecor(); } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) { mContentParent.removeAllViews(); } if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) { final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID, getContext()); transitionTo(newScene); } else { mLayoutInflater.inflate(layoutResID, mContentParent); } final Callback cb = getCallback(); if (cb != null && !isDestroyed()) { cb.onContentChanged(); } }
這裡可以拆成三個步驟來理解:
1. 如果還沒有 DecorView,就在 installDecor 中的 generateDecor() 建立 DecorView。
2. 將 View 添加到 DecorView 裡的 mContentParent 中。
3. 回呼 Activity 的 onContentChanged 介面。
經過以上操作,DecorView 雖然建立好了,但還沒有正式被加入到 Window 裡。真正把 View 加入 Window 的動作,發生在 Activity 的 makeVisible 方法中。當 Activity 進入 Resume 狀態時,會先呼叫 onResume,接著呼叫 makeVisible,程式碼如下:
void makeVisible() { if (!mWindowAdded) { ViewManager wm = getWindowManager(); wm.addView(mDecor, getWindow().getAttributes()); mWindowAdded = true; } mDecor.setVisibility(View.VISIBLE); }
就是透過上面的 addView 方法,把 View 真正添加進 Window。
一個 Window 對應一個 View 與一個 ViewRootImpl,Window 和 View 正是透過 ViewRootImpl 建立聯繫的。ViewRootImpl 並不獨立存在,其實體就是 View,只能透過 WindowManager 來操作。WindowManager 的實作類是 WindowManagerImpl,它並沒有直接實作增刪改三大操作,而是全部委託給 WindowManagerGlobal。addView 主要分為以下幾步:
第一步,檢查參數是否合法:
if (view == null) { throw new IllegalArgumentException("view must not be null"); } if (display == null) { throw new IllegalArgumentException("display must not be null"); } if (!(params instanceof WindowManager.LayoutParams)) { throw new IllegalArgumentException("Params must be WindowManager.LayoutParams"); }
第二步,建立 ViewRootImpl 並把 View 加入列表中:
root = new ViewRootImpl(view.getContext(), display); view.setLayoutParams(wparams); mViews.add(view); mRoots.add(root); mParams.add(wparams);
第三步,透過 ViewRootImpl 來更新介面並完成 Window 的添加:
root.setView(view, wparams, panelParentView);
setView 內部會透過 requestLayout() 完成非同步刷新:
public void requestLayout() { if (!mHandlingLayoutInLayoutRequest) { checkThread(); mLayoutRequested = true; scheduleTraversals(); } }
隨後透過 WindowSession 完成 Window 的添加過程。WindowSession 是一個 Binder 物件,真正的實作類是 Session,因此 Window 的添加本身就是一次 IPC 呼叫:
res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes, getHostVisibility(), mDisplay.getDisplayId(), mAttachInfo.mContentInsets, mAttachInfo.mStableInsets, mInputChannel);
在 Session 內部會透過 WindowManagerService 來完成 Window 的添加:
public int addToDisplay(IWindow window, int seq, WindowManager.LayoutParams attrs, int viewVisibility, int displayId, Rect outContentInsets, Rect outStableInsets, InputChannel outInputChannel) { return mService.addWindow(this, window, seq, attrs, viewVisibility, displayId, outContentInsets, outStableInsets, outInputChannel); }
WindowManagerService 內部會為每個應用保留一個獨立的 session。
來看 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 找到要刪除 View 的索引,這個過程就是遍歷陣列,接著再呼叫 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); } } }
真正的刪除動作是由 ViewRootImpl 完成的。WindowManager 提供了 removeViewImmediate 與 removeView 兩種刪除介面,分別代表同步刪除與非同步刪除,具體操作由 ViewRootImpl 的 die 方法負責:
boolean die(boolean immediate) { if (immediate && !mIsInTraversal) { doDie(); return false; } if (!mIsDrawing) { destroyHardwareRenderer(); } mHandler.sendEmptyMessage(MSG_DIE); return true; }
由此可見,若是呼叫 removeViewImmediate 就會立即執行 doDie;若是 removeView,則用 Handler 發送訊息,由 ViewRootImpl 內部的 Handler 處理後再呼叫 doDie。重點來看 doDie:
void doDie() { checkThread(); synchronized (this) { if (mRemoved) { return; } mRemoved = true; if (mAdded) { dispatchDetachedFromWindow(); } mAdded = false; } WindowManagerGlobal.getInstance().doRemoveView(this); }
它主要做四件事:
1. 進行資源回收相關工作,例如清理資料、回呼等。
2. 透過 Session 的 remove 方法刪除 Window,最終呼叫 WindowManagerService 的 removeWindow。
3. 呼叫 dispatchDetachedFromWindow,內部會觸發 onDetachedFromWindow() 與 onDetachedFromWindowInternal(),用於在 View 移除時回收資源。
4. 透過 doRemoveView 刷新資料、刪除相關物件,例如從 mRoots、mDyingViews 中移除對應項目。
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); } } }
最後來看 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); } }
它會透過 ViewRootImpl 的 setLayoutParams 更新版面參數,接著呼叫 scheduleTraversals 對 View 重新進行測量、布局與重繪,同時也會透過 WindowSession 更新 Window,這部分由 WindowManagerService 實作,原理與前面類似就不再贅述。至此,Window 的底層原始碼分析就全部完成了。
Android 資料儲存(三):SQLite 資料庫入門與 SQLiteOpenHelper 實作
Android 系統內建了一個輕量級資料庫:SQLite,這讓行動裝置上的本機資料存取變得相當容易。作為嵌入式資料庫引擎,SQLite 的設計目標正是「在資源有限的裝置上
Android 開發實戰:模擬 3D Touch 彈出效果完整教程
Android 開發實戰:模擬 3D Touch 彈出效果 3D Touch 是什麼效果,用過 iPhone 6s 的朋友應該都心中有數。本篇就來一步步復刻這個效果。 先
GitHub 上的 Android UI 靈感庫:開源介面設計參考
為什麼要參考開源 UI 專案 Android 開發入門容易,但要做出細節完整、互動自然的介面並不容易。GitHub 上有許多 UI 聚合專案,收錄大量開源元件與效果範例,
用代碼動態修改 Android View 尺寸的實戰做法
用代碼動態修改 Android View 尺寸的實戰做法 我們平時開發時,View 的寬高與位置大多直接在 Layout 的 XML 裡寫死。那麼什麼場景下非得跑到代碼裡