Window顧名思義就是窗口,Android Window的實現類是PhoneWindow。WindowManager是訪問Window的入口,通過它可以創建Window,WindowManager的具體實現在WindowService中,Window與WindowService之間的交互是一種IPC過程。Android中的界面都是通過Window來呈現的,比如Activity、Dialog和Toast等,他們的界面都是附加在Window上的,因此View的實際管理者是Window。
1.Window與WindowManager
在了解Window的工作機制之前我們先來看下如何使用WindowManager添加一個Window。
WindowManager windowManager = getWindowManager();
Button btAdd = new Button(this);
btAdd.setText("手動添加按鈕");
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT, 0, 0, PixelFormat.TRANSPARENT);
layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
layoutParams.gravity = Gravity.LEFT;
layoutParams.x = 100;
layoutParams.y = 200;
windowManager.addView(btAdd,layoutParams);
上面代碼是將一個Button添加到坐標(100,200)的位置。下面簡單介紹下WindowManager.LayoutParams中的flags與type這兩個參數。
flags表示的是Window的屬性,有很多選擇項,簡單介紹幾種。
FLAG_NOT_FOCUSABLE:
表示Window不需要獲取焦點,又不需要接受任何輸入事件,次標記還會同時啟用FLAG_NOT_TOUCH_MODAL,最終事件會傳遞給下層有焦點的Window。
FLAG_NOT_TOUCH_MODAL:
此模式下系統會將當前Window區域以外的單擊事件傳遞給底層的Window,當前區域以內的單擊事件則自己處理。
FLAG_SHOW_WHEN_LOCKED:
開啟當前模式,可以讓Window顯示在鎖屏界面上。
如果了解其他的屬性,建議還是看下源碼:
/** Window flag: as long as this window is visible to the user, allow
* the lock screen to activate while the screen is on.
* This can be used independently, or in combination with
* {@link #FLAG_KEEP_SCREEN_ON} and/or {@link #FLAG_SHOW_WHEN_LOCKED} */
public static final int FLAG_ALLOW_LOCK_WHILE_SCREEN_ON = 0x00000001;
/** Window flag: everything behind this window will be dimmed.
* Use {@link #dimAmount} to control the amount of dim. */
public static final int FLAG_DIM_BEHIND = 0x00000002;
/** Window flag: blur everything behind this window.
* @deprecated Blurring is no longer supported. */
@Deprecated
public static final int FLAG_BLUR_BEHIND = 0x00000004;
type表示Window的類型,一般Window有三種類型:應用Window、子Window和系統Window。應用類的Window對應著一個Activity。子Window是不能單獨存在的,他需要在特定的父Window之中,比如常見的Dialog就是一個子Window。系統Window需要聲明特殊的權限才能創建,比如Toast跟系統狀態欄等。
Window是分層的,每個Window都有對應的z-ordered,層級大的會覆蓋在層級小的Window的上面,這和HTML中的z-index的概念是完全一致的。在三類Window中,應用Window的層級范圍是1~99,子Window的層級范圍是1000~1999,系統Window的層級范圍是2000~2999,這些層級范圍對應著WindowManager.LayoutParams的type參數。如果想要Window位于所有Window的最頂層,那么采用較大的層級即可。很顯然系統Window的層級是最大的,而且系統層級有很多值,一般我們可以選用TYPE_SYSTEM_OVERLAY或者TYPE_SYSTEM_ERROR,如果采用TYPE_SYSTEM_ERROR,只需要為type參數指定這個層級即可:mLayoutParams.type = LayoutParams.TYPE_SYSTEM_ERROR;同時聲明權限:<uses-permissionandroid: name= "android.permission .SYSTEM_ALERT_WINDOW"/>。因為系統類型的Window是需要檢查權限的,如果不在AndroidManifest 中使用相應的權限,那么創建Window的時候就會報錯。
WindowManager的功能比較簡單,常用的就是三個方法:addView、updateViewLayout和removeView,這三個方法都定義在ViewManager中,WindowManager繼承了ViewManager。
/** Interface to let you add and remove child views to an Activity. To get an instance
* of this class, call {@link android.content.Context#getSystemService(java.lang.String) Context.getSystemService()}.
*/
public interface ViewManager
{
/**
* Assign the passed LayoutParams to the passed View and add the view to the window.
* <p>Throws {@link android.view.WindowManager.BadTokenException} for certain programming
* errors, such as adding a second view to a window without removing the first view.
* <p>Throws {@link android.view.WindowManager.InvalidDisplayException} if the window is on a
* secondary {@link Display} and the specified display can't be found
* (see {@link android.app.Presentation}).
* @param view The view to be added to this window.
* @param params The LayoutParams to assign to view.
*/
public void addView(View view, ViewGroup.LayoutParams params);
public void updateViewLayout(View view, ViewGroup.LayoutParams params);
public void removeView(View view);
}
對于我們開發者來說,WindowManager常用的就只有這三個功能,當然這三個方法也就足夠用了。WindowManager操作Window其實就是在操作里面的View。通過這些方法,我們可以實現諸如隨意拖拽位置的Window等效果。
2.Window的內部機制
Window是一個抽象類,每個Window都對應一個View跟一個ViewRootImpl,Window跟View是通過ViewRootImpl建立聯系的,因此Window并不實際存在,它是以View的形式存在的。從WindowManager的定義跟主要方法也能看出,View是Window存在的實體。下面就具體介紹下Window的addView、updateViewLayout和removeView。
2.1Window的添加過程。
Window的添加過程需要通過WindowManager的addView來實現,不過WindowManager是一個接口,真正實現是在WindowManagerImpl中,三個主要操作,先上源碼:
@Override
public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
applyDefaultToken(params);
mGlobal.addView(view, params, mContext.getDisplay(), mParentWindow);
}
@Override
public void updateViewLayout(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
applyDefaultToken(params);
mGlobal.updateViewLayout(view, params);
}
@Override
public void removeView(View view) {
mGlobal.removeView(view, false);
}
上面的源碼很明顯,WindowManagerImpl也沒有直接實現Window的三大操作,而是由WindowManagerGlobal來處理的,代碼段:private final WindowManagerGlobal mGlobal = WindowManagerGlobal.getInstance(); 可以看出,WindowManagerGlobal以工廠的形式向外提供自己的實例。WindowManagerImpl這種工作模式是典型的橋接模式,將所有的操作委托給WindowManagerGlobal來實現。具體看下addView的源碼:
1.檢查參數是否合法,子Window還需要調整布局:
......
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;
}
}
......
2.創建ViewRootImpl并將View添加到列表中
WindowManagerGlobal中的幾個重要列表:
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>();
mViews存儲的是Window中對應的View,mRoots則是Window中對應的對應的ViewRootImpl,mParams則是對應的布局。mDyingViews存儲的是正在被刪除的View。
......
root = new ViewRootImpl(view.getContext(), display);
view.setLayoutParams(wparams);
mViews.add(view);
mRoots.add(root);
mParams.add(wparams);
......
上面源碼表示了addView添加View的過程。
3.通過ViewRootImpl來更新界面,完成Window的添加過程
......
// 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;
}
......
ViewRootImpl的setView方法在界面View的時候有說到,在setView內部,通過requestLayout方法實現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();
......
接著通過WindowSession來完成Window的添加過程。下面的源碼中,mWindowSession是IWindowSession的實例,這是一個Binder對象,真正的實現類是Session,也就是說Window的添加過程是一次IPC調用。
try {
mOrigWindowType = mWindowAttributes.type;
mAttachInfo.mRecomputeGlobalAttributes = true;
collectViewAttributes();
res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
getHostVisibility(), mDisplay.getDisplayId(),
mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,
mAttachInfo.mOutsets, mInputChannel);
} catch (RemoteException e) {
mAdded = false;
mView = null;
mAttachInfo.mRootView = null;
mInputChannel = null;
mFallbackEventHandler.setView(null);
unscheduleTraversals();
setAccessibilityFocus(null, null);
throw new RuntimeException("Adding window failed", e);
} finally {
if (restore) {
attrs.restore();
}
}
Session內部會通過WindowManagerService來實現Window的添加過程。
介紹到這里,各位就發現,Window的添加請求是交給WindowManagerService去處理的,WindowManagerService內部會為每一個應用保留一個單獨的Session。具體的代碼的邏輯大家看下源碼,這里主要介紹部分源碼,還是以流程為主。
2.2Window的刪除過程
Window的刪除過程與添加過程一樣,都是先通過WindowManagerImpl然后通過WindowManagerGlobal來實現的:
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);
}
}
removeView的過程還是比較簡潔的,先findViewLocked找到待刪除的View的索引,這個索引是上面說的ArrayList mViews的index,然后刪除掉這個就可以了。
private int findViewLocked(View view, boolean required) {
final int index = mViews.indexOf(view);
if (required && index < 0) {
throw new IllegalArgumentException("View=" + view + " not attached to window manager");
}
return index;
}
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);
}
}
}
在WindowManager中提供了兩種刪除的接口:removeView跟removeViewImmediate,他們分別表示異步跟同步刪除,removeViewImmediate方法一般不會使用,以免刪除Window發生意外錯誤。我們重點看下異步刪除的情況。代碼段6可以看到,刪除操作是通過ViewRootImpl的die方法完成的,具體看下這個方法:
/**
* @param immediate True, do now if not in traversal. False, put on queue and do later.
* @return True, request has been queued. False, request has been completed.
*/
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方法只是發了一個請求,然后就返回了,再看代碼段6,View被加到mDyingViews中了。異步刪除可以看到發送了一個message,MSG_DIE,然后ViewRootImpl的handler會處理此消息然后調用die方法,同步的話就直接刪除了。這也是這兩種刪除方式的區別。真正刪除View的邏輯在doDie方法的dispatchDetachedFromWindow方法中。
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);
}
void dispatchDetachedFromWindow() {
if (mView != null && mView.mAttachInfo != null) {
mAttachInfo.mTreeObserver.dispatchOnWindowAttachedChange(false);
mView.dispatchDetachedFromWindow();
}
mAccessibilityInteractionConnectionManager.ensureNoConnection();
mAccessibilityManager.removeAccessibilityStateChangeListener(
mAccessibilityInteractionConnectionManager);
mAccessibilityManager.removeHighTextContrastStateChangeListener(
mHighContrastTextManager);
removeSendWindowContentChangedCallback();
destroyHardwareRenderer();
setAccessibilityFocus(null, null);
mView.assignParent(null);
mView = null;
mAttachInfo.mRootView = null;
mSurface.release();
if (mInputQueueCallback != null && mInputQueue != null) {
mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
mInputQueue.dispose();
mInputQueueCallback = null;
mInputQueue = null;
}
if (mInputEventReceiver != null) {
mInputEventReceiver.dispose();
mInputEventReceiver = null;
}
try {
mWindowSession.remove(mWindow);
} catch (RemoteException e) {
}
// Dispose the input channel after removing the window so the Window Manager
// doesn't interpret the input channel being closed as an abnormal termination.
if (mInputChannel != null) {
mInputChannel.dispose();
mInputChannel = null;
}
mDisplayManager.unregisterDisplayListener(mDisplayListener);
unscheduleTraversals();
}
從上面的源碼可以看到,dispatchDetachedFromWindow主要做了3件事:
(1)垃圾回收相關工作
(2)通過Session的remove方法刪除Window
(3)調用View的dispatchDetachedFromWindow方法,內部調用View的onDetachedFromWindow方法,這個也是做一些資源回收比較合適的時機,比如終止動畫、停止線程等。
最終doDie方法調用WindowManagerGlobal的doRemoveView刷新數據。
2.3Window的更新過程
介紹完Window的刪除,Window的更新過程直接上源碼:
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);
}
}
看源碼還是很簡單的,首先更新LayoutParams,然后通過ViewRootImpl的setLayoutParams更新ViewRootImpl中的LayoutParams,然后ViewRootImpl通過scheduleTraversals對View重新布局,包括測量,布局,繪制這三個過程。除了View本身重繪之外,ViewRootImpl會通過Session來更新Window視圖,同樣也是有WindowManagerService的relayoutWindow來實現的,也是一個IPC過程。