Android版本:7.0(API27)android
[TOC]程序員
窗口(不是指的Window類):這是一個純語義的說法,即程序員所看到的屏幕上的某個獨立的界面,好比一個帶有Title Bar的Activity界面、一個對話框、一個Menu菜單等,這些都稱之爲窗口。本書中所說的窗口管理通常也都泛指全部這些窗口,在Android的英文相關文章中則直接使用Window這個單詞。而從WmS的角度來說,窗口是接收用戶消息的最小單元,WmS內部用特定的類表示一個窗口,以實現對窗口的管理。WmS接收到用戶消息後,首先要判斷這個消息屬於哪一個窗口,而後經過IPC調用把這個消息傳遞給客戶端的ViewRoot類。bash
Window類:該類在android.view包中,是一個abstract類,該類抽象了「客戶端窗口」的基本操做,而且定義了一組Callback接口,Activity類就是經過實現這個Callback接口以得到對消息處理的機會,由於消息最初是由WmS傳遞給View對象的。app
ViewRoot類:該類在android.view包中,客戶端申請建立窗口時須要一個客戶端代理,用以和WmS進行交互,ViewRoot內部類W就是完成這個功能的。WmS所管理的每個窗口都會對應一個ViewRoot類。框架
W類:該類是ViewRoot類的一個內部類,繼承於Binder,用於向WmS提供一個IPC接口,從而讓WmS控制窗口客戶端的行爲。異步
描述一個窗口之因此使用這麼多類的緣由在於,窗口的概念存在於客戶端和服務端(WmS)之中,而且Framework又定義了一個Window類,這很容易讓人產生混淆,實際上WmS所管理的窗口和Window類沒有任何關係。ide
Activity、DecorView與Window、WindowMananger的關係以下圖所示:oop
當ActivityThread接收到AmS發送start某個Activity後,就會建立指定的Activity對象。Activity又會建立PhoneWindow類→DecorView類→建立相應的View或者ViewGroup。建立完成後,Activity須要把建立好的界面顯示到屏幕上,因而調用WindowManager類,後者因而建立一個ViewRootImpl對象,該對象實際上建立了ViewRootImpl類和W類,建立ViewRootImpl對象後,WindowManager再調用WmS提供的遠程接口完成添加一個窗口並顯示到屏幕上。
這其中ViewRootImpl很是重要,它具有以下幾個核心功能:佈局
mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
mFloatingButton = new Button(this);
mFloatingButton.setText("click me");
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);
複製代碼
上述代碼將一個Button添加到頻幕座標(100,300)的位置上。其中WindowManager.LayoutParams的兩個參數flags和type比較重要。post
應用類Window對應着一個Activity。子Window不能單獨存在,它須要附屬在特定的父Window中,好比Dialog就是一個子Window。系統Window是須要聲明權限才能建立的Window,好比Toast和系統狀態欄這些都是系統Window。
Window是分層的,每一個Window都有對應的z-ordered,層級大的會覆蓋在層級小的Window上。在三類Window中,應用Window的層級範圍是1~99,子Window的層級範圍是1000~1999,系統Window的層級範圍是2000~2999。很顯然系統Window的層級是最大的,並且系統層級有不少值,通常咱們能夠選用TYPE_SYSTEM_ERROR或者TYPE_SYSTEM_OVERLAY,另外重要的是要記得在清單文件中聲明權限。
WindowManager所提供的功能很簡單,經常使用的只有三個方法,即添加View、更新View和刪除View,這三個方法定義在ViewManager中,而WindowManager繼承了ViewManager。
public interface ViewManager
{
public void addView(View view, ViewGroup.LayoutParams params);
public void updateViewLayout(View view, ViewGroup.LayoutParams params);
public void removeView(View view);
}
複製代碼
Window是一個抽象的概念,每個Window都對應着一個View和一個ViewRootImpl,Window和View經過ViewRootImpl來創建聯繫,所以Window並非實際存在的,它是以View的形式存在,這點從WindowManager的定義能夠看出,它提供的三個接口方法都是針對View的,這說明View纔是WIndow存在的實體。在實際使用中沒法直接訪問Window,對WIndow的訪問必須經過WindowManager。爲了分析Window的內部機制,這裏從Window的添加、刪除以及更新去分析。
WindowManager的實現類是WindowManagerImpl,因此咱們直接看WindowManagerImpl.addView()方法:
public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
applyDefaultToken(params);
mGlobal.addView(view, params, mContext.getDisplay(), mParentWindow);
}
複製代碼
addView內部藉助mGlobal(WindowManagerGlobal)的addView,WindowManagerGlobal是一個單例,mGlobal.addView中用到了幾個重要字段:
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>();
private final ArraySet<View> mDyingViews = new ArraySet<View>();
複製代碼
public void addView(View view, ViewGroup.LayoutParams params,
Display display, Window parentWindow) {
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");
}
final WindowManager.LayoutParams wparams = (WindowManager.LayoutParams) params;
if (parentWindow != null) {
parentWindow.adjustLayoutParamsForSubWindow(wparams);
} else {
// If there's no parent, then hardware acceleration for this view is // set from the application's hardware acceleration setting.
final Context context = view.getContext();
if (context != null
&& (context.getApplicationInfo().flags
& ApplicationInfo.FLAG_HARDWARE_ACCELERATED) != 0) {
wparams.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
}
}
ViewRootImpl root;
View panelParentView = null;
synchronized (mLock) {
// Start watching for system property changes.
if (mSystemPropertyUpdater == null) {
mSystemPropertyUpdater = new Runnable() {
@Override public void run() {
synchronized (mLock) {
for (int i = mRoots.size() - 1; i >= 0; --i) {
mRoots.get(i).loadSystemProperties();
}
}
}
};
SystemProperties.addChangeCallback(mSystemPropertyUpdater);
}
int index = findViewLocked(view, false);
if (index >= 0) {
if (mDyingViews.contains(view)) {
// Don't wait for MSG_DIE to make it's way through root's queue. mRoots.get(index).doDie(); } else { throw new IllegalStateException("View " + view + " has already been added to the window manager."); } // The previous removeView() had not completed executing. Now it has. } // If this is a panel window, then find the window it is being // attached to for future reference. if (wparams.type >= WindowManager.LayoutParams.FIRST_SUB_WINDOW && wparams.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) { final int count = mViews.size(); for (int i = 0; i < count; i++) { if (mRoots.get(i).mWindow.asBinder() == wparams.token) { panelParentView = mViews.get(i); } } } root = new ViewRootImpl(view.getContext(), display); view.setLayoutParams(wparams); mViews.add(view); mRoots.add(root); mParams.add(wparams); // do this last because it fires off messages to start doing things try { root.setView(view, wparams, panelParentView); } catch (RuntimeException e) { // BadTokenException or InvalidDisplayException, clean up. if (index >= 0) { removeViewLocked(index, true); } throw e; } } } 複製代碼
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);
複製代碼
在「窗口工做原理」中咱們已經說明的ViewRootImpl的重要做用,ViewRootImpl源碼比較複雜還設計到Binder原理,因此爲了避免因深刻細節而打亂咱們的分析節奏,咱們對ViewRootImpl的分析只看流程框架。下面咱們繼續看ViewRootImpl.setView:
public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
.....
mView = view;
.....
// Schedule the first layout -before- adding to the window
// manager, to make sure we do the relayout before receiving
// any other events from the system.
requestLayout();
.....
res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
getHostVisibility(), mDisplay.getDisplayId(),
mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,
mAttachInfo.mOutsets, mInputChannel);
}
複製代碼
ViewRootImpl.setView的源碼也很長,咱們將關鍵的幾個步驟羅列出來。
在這裏爲後續「視圖繪製」一文作個鋪墊,進一步看一下requestLayout的源碼
@Override
public void requestLayout() {
if (!mHandlingLayoutInLayoutRequest) {
checkThread();
mLayoutRequested = true;
scheduleTraversals();
}
}
複製代碼
調用scheduleTraversals開始繪製
void scheduleTraversals() {
if (!mTraversalScheduled) {
mTraversalScheduled = true;
mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
mChoreographer.postCallback(
Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
if (!mUnbufferedInputDispatch) {
scheduleConsumeBatchedInput();
}
notifyRendererOfFramePending();
pokeDrawLockIfNeeded();
}
}
複製代碼
這裏執行了一個異步任務mTraversalRunnable,繼續看看mTraversalRunnable
final class TraversalRunnable implements Runnable {
@Override
public void run() {
doTraversal();
}
}
複製代碼
void doTraversal() {
if (mTraversalScheduled) {
mTraversalScheduled = false;
mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);
if (mProfile) {
Debug.startMethodTracing("ViewAncestor");
}
performTraversals();
if (mProfile) {
Debug.stopMethodTracing();
mProfile = false;
}
}
}
複製代碼
看到performTraversals,它其實就是整個視圖繪製的開始;在這裏咱們先對performTraversals有個印象,後面「視圖繪製」一文會進一步分析performTraversals的。
Window的刪除過程和添加過程同樣,經過WindowManagerImpl調用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);
}
}
}
複製代碼
removeViewLocked()是經過ViewRootImpl來完成刪除操做的。WindowManager中提供了兩種刪除接口,removeView()和removeViewImmediate(),他們分表表示異步刪除和同步刪除。具體的刪除操做由ViewRootImpl的die()來完成:
boolean die(boolean immediate) {
// Make sure we do execute immediately if we are in the middle of a traversal or the damage
// done by dispatchDetachedFromWindow will cause havoc on return.
if (immediate && !mIsInTraversal) {
doDie();
return false;
}
if (!mIsDrawing) {
destroyHardwareRenderer();
} else {
Log.e(mTag, "Attempting to destroy the window while drawing!\n" +
" window=" + this + ", title=" + mWindowAttributes.getTitle());
}
mHandler.sendEmptyMessage(MSG_DIE);
return true;
}
複製代碼
在異步刪除的狀況下,die()只是發送了一個請求刪除的消息就返回了,這時候View尚未完成刪除操做,因此最後將它添加到mDyingViews中,mDyingViews表示待刪除的View的集合。若是是同步刪除,不發送消息就直接調用dodie():
void doDie() {
checkThread();
if (LOCAL_LOGV) Log.v(mTag, "DIE in " + this + " of " + mSurface);
synchronized (this) {
if (mRemoved) {
return;
}
mRemoved = true;
if (mAdded) {
dispatchDetachedFromWindow();
}
if (mAdded && !mFirst) {
destroyHardwareRenderer();
if (mView != null) {
int viewVisibility = mView.getVisibility();
boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
if (mWindowAttributesChanged || viewVisibilityChanged) {
// If layout params have been changed, first give them
// to the window manager to make sure it has the correct
// animation info.
try {
if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
& WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) {
mWindowSession.finishDrawing(mWindow);
}
} catch (RemoteException e) {
}
}
mSurface.release();
}
}
mAdded = false;
}
WindowManagerGlobal.getInstance().doRemoveView(this);
}
複製代碼
在dodie()內部會調用dispatchDetachedFromWindow(),真正刪除View的邏輯就在dispatchDetachedFromWindow()中:
void dispatchDetachedFromWindow() {
if (mView != null && mView.mAttachInfo != null) {
mAttachInfo.mTreeObserver.dispatchOnWindowAttachedChange(false);
mView.dispatchDetachedFromWindow();
}
.....
try {
mWindowSession.remove(mWindow);
} catch (RemoteException e) {
}
}
複製代碼
dispatchDetachedFromWindow()主要作幾件事情:
updateViewLayout()作的事情就比較簡單了,首先先更新View的LayoutParams,接着更新ViewRootImpl的LayoutParams。ViewRootImpl會在setLayoutParams()中調用scheduleTraversals()來對View從新佈局重繪。除此以外ViewRootImpl還會經過WindowSession來更新Window的視圖,這個過程最終由WindowManagerService的relayoutWindow()來具體實現,這一樣是一個IPC過程。具體代碼執行邏輯你們能夠自行查看一下。