美文网首页
Android WMS WindowState显示次序

Android WMS WindowState显示次序

作者: android_coder | 来源:发表于2020-06-29 19:58 被阅读0次

    窗口的显示在手机上,是以屏幕左上角为原点,向右为X轴,向下为Y轴,垂直与屏幕表面并指向屏幕外为Z轴。多个窗口依照顺序排列在Z轴上显示,称为Z order。

    1:WindowState的次序
    WindowState(WindowManagerService service, Session s, IWindow c, WindowToken token,
                WindowState parentWindow, int appOp, int seq, WindowManager.LayoutParams a,
                int viewVisibility, int ownerId, boolean ownerCanAddInternalSystemWindow,
                PowerManagerWrapper powerManagerWrapper) {
            super(service);
            .........................
            if (mAttrs.type >= FIRST_SUB_WINDOW && mAttrs.type <= LAST_SUB_WINDOW) {//子窗口
                // The multiplier here is to reserve space for multiple
                // windows in the same type layer.
                mBaseLayer = mPolicy.getWindowLayerLw(parentWindow)
                        * TYPE_LAYER_MULTIPLIER + TYPE_LAYER_OFFSET;
                mSubLayer = mPolicy.getSubWindowLayerFromTypeLw(a.type);
                mIsChildWindow = true;
                if (DEBUG_ADD_REMOVE) Slog.v(TAG, "Adding " + this + " to " + parentWindow);
                parentWindow.addChild(this, sWindowSubLayerComparator);
                mLayoutAttached = mAttrs.type !=    WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
                mIsImWindow = parentWindow.mAttrs.type == TYPE_INPUT_METHOD
                        || parentWindow.mAttrs.type == TYPE_INPUT_METHOD_DIALOG;
                mIsWallpaper = parentWindow.mAttrs.type == TYPE_WALLPAPER;
            } else {
                // The multiplier here is to reserve space for multiple
                // windows in the same type layer.
                mBaseLayer = mPolicy.getWindowLayerLw(this)
                        * TYPE_LAYER_MULTIPLIER + TYPE_LAYER_OFFSET;
                mSubLayer = 0;
                mIsChildWindow = false;
                mLayoutAttached = false;
                mIsImWindow = mAttrs.type == TYPE_INPUT_METHOD
                        || mAttrs.type == TYPE_INPUT_METHOD_DIALOG;
                mIsWallpaper = mAttrs.type == TYPE_WALLPAPER;
            }
            mIsFloatingLayer = mIsImWindow || mIsWallpaper;
            .........................
        }
    

    在WindowState的构造方法中根据窗口类型确定baseLayer和subLayer, 其中mBaseLayer和mSubLayer可以决定该窗口的显示次序

    1.1:BaseLayer的确定

    BaseLayer用来确定该窗口在所有窗口DisplayContent中的显示次序

    default int getWindowLayerFromTypeLw(int type, boolean canAddInternalSystemWindow) {
            if (type >= FIRST_APPLICATION_WINDOW && type <= LAST_APPLICATION_WINDOW) {
                return APPLICATION_LAYER;
            }
    
            switch (type) {
                case TYPE_WALLPAPER:
                    // wallpaper is at the bottom, though the window manager may move it.
                    return  1;
                case TYPE_PRESENTATION:
                case TYPE_PRIVATE_PRESENTATION:
                    return  APPLICATION_LAYER;
                case TYPE_DOCK_DIVIDER:
                    return  APPLICATION_LAYER;
                case TYPE_QS_DIALOG:
                    return  APPLICATION_LAYER;
                case TYPE_PHONE:
                    return  3;
                case TYPE_SEARCH_BAR:
                case TYPE_VOICE_INTERACTION_STARTING:
                    return  4;
                case TYPE_VOICE_INTERACTION:
                    // voice interaction layer is almost immediately above apps.
                    return  5;
                case TYPE_INPUT_CONSUMER:
                    return  6;
                case TYPE_SYSTEM_DIALOG:
                    return  7;
                case TYPE_TOAST:
                    // toasts and the plugged-in battery thing
                    return  8;
                case TYPE_PRIORITY_PHONE:
                    // SIM errors and unlock.  Not sure if this really should be in a high layer.
                    return  9;
                case TYPE_SYSTEM_ALERT:
                    // like the ANR / app crashed dialogs
                    return  canAddInternalSystemWindow ? 11 : 10;
                case TYPE_APPLICATION_OVERLAY:
                    return  12;
                case TYPE_DREAM:
                    // used for Dreams (screensavers with TYPE_DREAM windows)
                    return  13;
                case TYPE_INPUT_METHOD:
                    // on-screen keyboards and other such input method user interfaces go here.
                    return  14;
                case TYPE_INPUT_METHOD_DIALOG:
                    // on-screen keyboards and other such input method user interfaces go here.
                    return  15;
                case TYPE_STATUS_BAR:
                    return  17;
                case TYPE_STATUS_BAR_PANEL:
                    return  18;
                case TYPE_STATUS_BAR_SUB_PANEL:
                    return  19;
                case TYPE_KEYGUARD_DIALOG:
                    return  20;
                case TYPE_VOLUME_OVERLAY:
                    // the on-screen volume indicator and controller shown when the user
                    // changes the device volume
                    return  21;
                case TYPE_SYSTEM_OVERLAY:
                    // the on-screen volume indicator and controller shown when the user
                    // changes the device volume
                    return  canAddInternalSystemWindow ? 22 : 11;
                case TYPE_NAVIGATION_BAR:
                    // the navigation bar, if available, shows atop most things
                    return  23;
                case TYPE_NAVIGATION_BAR_PANEL:
                    // some panels (e.g. search) need to show on top of the navigation bar
                    return  24;
                case TYPE_SCREENSHOT:
                    // screenshot selection layer shouldn't go above system error, but it should cover
                    // navigation bars at the very least.
                    return  25;
                case TYPE_SYSTEM_ERROR:
                    // system-level error dialogs
                    return  canAddInternalSystemWindow ? 26 : 10;
                case TYPE_MAGNIFICATION_OVERLAY:
                    // used to highlight the magnified portion of a display
                    return  27;
                case TYPE_DISPLAY_OVERLAY:
                    // used to simulate secondary display devices
                    return  28;
                case TYPE_DRAG:
                    // the drag layer: input for drag-and-drop is associated with this window,
                    // which sits above all other focusable windows
                    return  29;
                case TYPE_ACCESSIBILITY_OVERLAY:
                    // overlay put by accessibility services to intercept user interaction
                    return  30;
                case TYPE_SECURE_SYSTEM_OVERLAY:
                    return  31;
                case TYPE_BOOT_PROGRESS:
                    return  32;
                case TYPE_POINTER:
                    // the (mouse) pointer layer
                    return  33;
                default:
                    Slog.e("WindowManager", "Unknown window type: " + type);
                    return APPLICATION_LAYER;
            }
        }
    
    1.2:subLayer

    subLayer只针对子窗口有效,子窗口有可能在父窗口的下面,也有可能在父窗口的上面

        default int getSubWindowLayerFromTypeLw(int type) {
            switch (type) {
                case TYPE_APPLICATION_PANEL:
                case TYPE_APPLICATION_ATTACHED_DIALOG:
                    return APPLICATION_PANEL_SUBLAYER;
                case TYPE_APPLICATION_MEDIA:
                    return APPLICATION_MEDIA_SUBLAYER;
                case TYPE_APPLICATION_MEDIA_OVERLAY:
                    return APPLICATION_MEDIA_OVERLAY_SUBLAYER;
                case TYPE_APPLICATION_SUB_PANEL:
                    return APPLICATION_SUB_PANEL_SUBLAYER;
                case TYPE_APPLICATION_ABOVE_SUB_PANEL:
                    return APPLICATION_ABOVE_SUB_PANEL_SUBLAYER;
            }
            Slog.e("WindowManager", "Unknown sub-window type: " + type);
            return 0;
        }
    
    2:DisplayContent中的次序

    DisplayContent默认情况下会创建四种类型的容器来存储当前显示设备上的窗口,这四种容器分别是存储壁纸窗口,应用程序窗口,系统窗口和输入法窗口

    /** The containers below are the only child containers the display can have. */
        // Contains all window containers that are related to apps (Activities)
        private final TaskStackContainers mTaskStackContainers = new TaskStackContainers(mService);
        // Contains all non-app window containers that should be displayed above the app containers
        // (e.g. Status bar)
        private final AboveAppWindowContainers mAboveAppWindowsContainers =
                new AboveAppWindowContainers("mAboveAppWindowsContainers", mService);
        // Contains all non-app window containers that should be displayed below the app containers
        // (e.g. Wallpaper).
        private final NonAppWindowContainers mBelowAppWindowsContainers =
                new NonAppWindowContainers("mBelowAppWindowsContainers", mService);
        // Contains all IME window containers. Note that the z-ordering of the IME windows will depend
        // on the IME target. We mainly have this container grouping so we can keep track of all the IME
        // window containers together and move them in-sync if/when needed. We use a subclass of
        // WindowContainer which is omitted from screen magnification, as the IME is never magnified.
        private final NonMagnifiableWindowContainers mImeWindowsContainers =
                new NonMagnifiableWindowContainers("mImeWindowsContainers", mService);
    

    在窗口创建的时候被添加到对应的容器中,具体在

     if (token.asAppWindowToken() == null) {//如果token不是AppWindowToken
                // Add non-app token to container hierarchy on the display. App tokens are added through
                // the parent container managing them (e.g. Tasks).
                switch (token.windowType) {
                    case TYPE_WALLPAPER:
                        mBelowAppWindowsContainers.addChild(token);
                        break;
                    case TYPE_INPUT_METHOD:
                    case TYPE_INPUT_METHOD_DIALOG:
                        mImeWindowsContainers.addChild(token);
                        break;
                    default:
                        mAboveAppWindowsContainers.addChild(token);
                        break;
                }
            }
    

    依据就是窗口类型


    显示次序.png
    3:窗口次序的二次调整

    窗口次序的调整时机应该是有新窗口被添加或是旧的窗口被移除,不管是什么类型的窗口被添加到wms中都是走addWindow方法

    final boolean suspended = mPmInternal.isPackageSuspended(win.getOwningPackage(),
                        UserHandle.getUserId(win.getOwningUid()));
                win.setHiddenWhileSuspended(suspended);
                final boolean hideSystemAlertWindows = !mHidingNonSystemOverlayWindows.isEmpty();
    win.setForceHideNonSystemOverlayWindowIfNeeded(hideSystemAlertWindows);
                final AppWindowToken aToken = token.asAppWindowToken();
                if (type == TYPE_APPLICATION_STARTING && aToken != null) {
                    aToken.startingWindow = win;
                    if (DEBUG_STARTING_WINDOW) Slog.v (TAG_WM, "addWindow: " + aToken
                            + " startingWindow=" + win);
                }
                boolean imMayMove = true;
                win.mToken.addWindow(win);
                if (type == TYPE_INPUT_METHOD) {
                    win.mGivenInsetsPending = true;
                    setInputMethodWindowLocked(win);
                    imMayMove = false;
                } else if (type == TYPE_INPUT_METHOD_DIALOG) {
                    displayContent.computeImeTarget(true /* updateImeTarget */);
                    imMayMove = false;
                } else {
                    if (type == TYPE_WALLPAPER) {         displayContent.mWallpaperController.clearLastWallpaperTimeoutTime();
                        displayContent.pendingLayoutChanges |= FINISH_LAYOUT_REDO_WALLPAPER;
                    } else if ((attrs.flags&FLAG_SHOW_WALLPAPER) != 0) {
                        displayContent.pendingLayoutChanges |= FINISH_LAYOUT_REDO_WALLPAPER;
                    } else if (displayContent.mWallpaperController.isBelowWallpaperTarget(win)) {
                        // If there is currently a wallpaper being shown, and
                        // the base layer of the new window is below the current
                        // layer of the target window, then adjust the wallpaper.
                        // This is to avoid a new window being placed between the
                        // wallpaper and its target.
                        displayContent.pendingLayoutChanges |= FINISH_LAYOUT_REDO_WALLPAPER;
                    }
                }
    

    这个地方有两个关键点
    3.1:win.mToken.addWindow(win);添加到windowContainer中,此时会导致容器中的其他窗口位置会发生变化

    WindowToken.java
    void addWindow(final WindowState win) {
            if (DEBUG_FOCUS) Slog.d(TAG_WM,
                    "addWindow: win=" + win + " Callers=" + Debug.getCallers(5));
            if (win.isChildWindow()) {//如果是子窗口,应该添加到父窗口的容器中
                // Child windows are added to their parent windows.
                return;
            }
            if (!mChildren.contains(win)) {//如果WindowContainer中没有添加过
                if (DEBUG_ADD_REMOVE) Slog.v(TAG_WM, "Adding " + win + " to " + this);
                addChild(win, mWindowComparator);
                mService.mWindowsChanged = true;
                // TODO: Should we also be setting layout needed here and other places?
            }
        }
     WindowContainer.java
     protected void addChild(E child, Comparator<E> comparator) {
            if (child.getParent() != null) {
                throw new IllegalArgumentException("addChild: container=" + child.getName()
                        + " is already a child of container=" + child.getParent().getName()
                        + " can't add to container=" + getName());
            }
            int positionToAdd = -1;
            if (comparator != null) {
                final int count = mChildren.size();
                for (int i = 0; i < count; i++) {
                    if (comparator.compare(child, mChildren.get(i)) < 0) {
                        positionToAdd = i;
                        break;
                    }
                }
            }
            if (positionToAdd == -1) {
                mChildren.add(child);
            } else {
                mChildren.add(positionToAdd, child);
            }
            onChildAdded(child);
            // Set the parent after we've actually added a child in case a subclass depends on this.
            child.setParent(this);
        }
        //自定义的Comparator
        private final Comparator<WindowState> mWindowComparator =
                (WindowState newWindow, WindowState existingWindow) -> {
            final WindowToken token = WindowToken.this;
            if (newWindow.mToken != token) {//如果token不同,那么肯定不是一个容器
                throw new IllegalArgumentException("newWindow=" + newWindow
                        + " is not a child of token=" + token);
            }
            if (existingWindow.mToken != token) {//确保容器相同
                throw new IllegalArgumentException("existingWindow=" + existingWindow
                        + " is not a child of token=" + token);
            }
            return isFirstChildWindowGreaterThanSecond(newWindow, existingWindow) ? 1 : -1;
        };
        protected boolean isFirstChildWindowGreaterThanSecond(WindowState newWindow,
                WindowState existingWindow) {
            // New window is considered greater if it has a higher or equal base layer.
            return newWindow.mBaseLayer >= existingWindow.mBaseLayer;//比较baseLayer值
        }
    

    上面的逻辑也就是根据窗口的baseLayer值来决定其存储的位置
    3.2: DisplayContent.computeImeTarget()计算输入法的目标窗口,输入法窗口永远都是在需要输入法窗口的上面,此时也会导致窗口的位置发生变化

     WindowState computeImeTarget(boolean updateImeTarget) {
            if (mService.mInputMethodWindow == null) {//如果输入法窗口为null
                // There isn't an IME so there shouldn't be a target...That was easy!
                if (updateImeTarget) {//更新输入法目标窗口
                    //将输入法的目标窗口设置为null
                    setInputMethodTarget(null, mService.mInputMethodTargetWaitingAnim);
                }
                return null;
            }
            final WindowState curTarget = mService.mInputMethodTarget;
            if (!canUpdateImeTarget()) {//如果不能更新输入法目标窗口
                return curTarget;//当前的输入法目标窗口
            }
            mUpdateImeTarget = updateImeTarget;//更新输入法的全局控制变量
            WindowState target = getWindow(mComputeImeTargetPredicate);//找到可以成为输入法目标窗口的窗口
            if (target != null && target.mAttrs.type == TYPE_APPLICATION_STARTING) {//如果是应用的启动窗口
                final AppWindowToken token = target.mAppToken;
                if (token != null) {
                    final WindowState betterTarget = token.getImeTargetBelowWindow(target);//找到启动窗口下面的一个可作为输入法目标窗口的窗口
                    if (betterTarget != null) {
                        target = betterTarget;
                    }
                }
            }
            if (curTarget != null && curTarget.isDisplayedLw() && curTarget.isClosing()
                    && (target == null || target.isActivityTypeHome())) {
                return curTarget;
            }//如果当前窗口正在退出并且新的目标窗口是桌面,为了避免屏幕闪烁,依然将输入法的目标窗口设为前一个窗口上
            if (target == null) {
                if (updateImeTarget) {
                    setInputMethodTarget(null, mService.mInputMethodTargetWaitingAnim);
                }
                return null;
            }
            if (updateImeTarget) {
                AppWindowToken token = curTarget == null ? null : curTarget.mAppToken;
                if (token != null) {
                    WindowState highestTarget = null;
                    if (token.isSelfAnimating()) {
                        highestTarget = token.getHighestAnimLayerWindow(curTarget);//获取容器中anim层级最高的窗口
                    }
                    if (highestTarget != null) {
                        final AppTransition appTransition = mService.mAppTransition;
                        if (appTransition.isTransitionSet()) {
                            setInputMethodTarget(highestTarget, true);
                            return highestTarget;
                        } else if (highestTarget.mWinAnimator.isAnimationSet() &&
                                highestTarget.mWinAnimator.mAnimLayer > target.mWinAnimator.mAnimLayer) {
                            setInputMethodTarget(highestTarget, true);
                            return highestTarget;
                        }
                    }
                }
                setInputMethodTarget(target, false);
            }
            return target;
        }
        private void setInputMethodTarget(WindowState target, boolean targetWaitingAnim) {
            if (target == mService.mInputMethodTarget
                    && mService.mInputMethodTargetWaitingAnim == targetWaitingAnim) {
                return;
            }
            mService.mInputMethodTarget = target;
            mService.mInputMethodTargetWaitingAnim = targetWaitingAnim;
            assignWindowLayers(false /* setLayoutNeeded */);//分配计算窗口层级
        }
    
    4:WindowContainer::assignWindowLayers
     void assignWindowLayers(boolean setLayoutNeeded) {
            Trace.traceBegin(Trace.TRACE_TAG_WINDOW_MANAGER, "assignWindowLayers");
            assignChildLayers(getPendingTransaction());
            if (setLayoutNeeded) {
                setLayoutNeeded();
            }
            // We accumlate the layer changes in-to "getPendingTransaction()" but we defer
            // the application of this transaction until the animation pass triggers
            // prepareSurfaces. This allows us to synchronize Z-ordering changes with
            // the hiding and showing of surfaces.
            scheduleAnimation();
            Trace.traceEnd(Trace.TRACE_TAG_WINDOW_MANAGER);
        }
    
        void assignChildLayers(Transaction t) {
            int layer = 0;
            // We use two passes as a way to promote children which
            // need Z-boosting to the end of the list.
            for (int j = 0; j < mChildren.size(); ++j) {
                final WindowContainer wc = mChildren.get(j);
                wc.assignChildLayers(t);
                if (!wc.needsZBoost()) {//不需要动画的
                    wc.assignLayer(t, layer++);
                }
            }
            for (int j = 0; j < mChildren.size(); ++j) {
                final WindowContainer wc = mChildren.get(j);
                if (wc.needsZBoost()) {//需要动画的
                    wc.assignLayer(t, layer++);
                }
            }
        }
    

    通过上面的两次for循环上面的layer++保证了需要动画的在不需要动画的上面,通过调整分离了需要做动画和不需要做动画的

    5:概述

    窗口的层级跟窗口的类型有关,在窗口被添加过程中会根据情况来决定在DisplayContent里面的位置

    相关文章

      网友评论

          本文标题:Android WMS WindowState显示次序

          本文链接:https://www.haomeiwen.com/subject/jgiwfktx.html