Android Window與WindowManager 理解與源碼分析

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過程。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,517評論 6 539
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,087評論 3 423
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,521評論 0 382
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,493評論 1 316
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,207評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,603評論 1 325
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,624評論 3 444
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,813評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,364評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,110評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,305評論 1 371
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,874評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,532評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,953評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,209評論 1 291
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,033評論 3 396
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,268評論 2 375

推薦閱讀更多精彩內容