Android 11 --关于Toast的异常

发布时间 2023-11-13 19:05:34作者: 僵小七
WMS 服务关于Toast异常

Window和View的关系:
Window 是View的载体。每个view树都可以看成一个window。
view树中的每个view显示次序是固定,activity里面设置一个布局xml文件,最顶层的布局就是view树的根节点。
一个自定义布局的Dialog,Dialog的顶层布局就不属于activity的View树,这是2个View树,所以是2个Window。

Window 的一些重要属性:
Window的 type 属性决定了window的显示次序,大致分为1-1000 为低层,1001-2000为中层,2000以上为高层。

应用程序窗口:应用程序窗口一般位于最底层,z-order在1-99
子窗口:子窗口一般是显示在应用窗口之上,z-order在1000-1999
系统级窗口:系统级窗口一般位于最顶层,不会被其他的window遮住,如Toast,z-order在2000-2999

z-order越大,window显示越高,高度高的window会覆盖高度低的window,跟搭积木一样。

Window的flag属性 flag标志控制window的显示,Window的softInputMode属性,当软键盘弹出是,对当前window的控制。

Android 11 分屏(不同的displayId) 显示 Toast造成的SystemUI的ANR

bug报错日志:

11-09 11:26:15.814  9306  9306 W ToastUI : Attempt to hide non-current toast from package com.acloud.stub.localmusic
11-09 11:26:15.823  1392  5481 W WindowManager: Attempted to add window to a display for which the application does not have access: 0.  Aborting.
11-09 11:26:15.824  9306  9306 D AndroidRuntime: Shutting down VM
11-09 11:26:15.825  9306  9306 E AndroidRuntime: FATAL EXCEPTION: main
11-09 11:26:15.825  9306  9306 E AndroidRuntime: Process: com.android.systemui, PID: 9306
11-09 11:26:15.825  9306  9306 E AndroidRuntime: android.view.WindowManager$InvalidDisplayException: Unable to add window android.view.ViewRootImpl$W@6061d4d -- the specified display can not be found
11-09 11:26:15.825  9306  9306 E AndroidRuntime: 	at android.view.ViewRootImpl.setView(ViewRootImpl.java:1101)
11-09 11:26:15.825  9306  9306 E AndroidRuntime: 	at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:409)
11-09 11:26:15.825  9306  9306 E AndroidRuntime: 	at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:110)
11-09 11:26:15.825  9306  9306 E AndroidRuntime: 	at android.widget.ToastPresenter.show(ToastPresenter.java:210)
11-09 11:26:15.825  9306  9306 E AndroidRuntime: 	at com.android.systemui.toast.ToastUI.showToast(ToastUI.java:96)
11-09 11:26:15.825  9306  9306 E AndroidRuntime: 	at com.android.systemui.statusbar.CommandQueue$H.handleMessage(CommandQueue.java:1285)
11-09 11:26:15.825  9306  9306 E AndroidRuntime: 	at android.os.Handler.dispatchMessage(Handler.java:106)
11-09 11:26:15.825  9306  9306 E AndroidRuntime: 	at android.os.Looper.loop(Looper.java:223)
11-09 11:26:15.825  9306  9306 E AndroidRuntime: 	at android.app.ActivityThread.main(ActivityThread.java:7705)
11-09 11:26:15.825  9306  9306 E AndroidRuntime: 	at java.lang.reflect.Method.invoke(Native Method)
11-09 11:26:15.825  9306  9306 E AndroidRuntime: 	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
11-09 11:26:15.825  9306  9306 E AndroidRuntime: 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:952)

根据日志跟踪代码进行分析:
当时看到这个报错日志也是有点看不明白,不明白为什么Toast的显示,和system UI有什么关系。
但是报错全是标记到这里了,那就跟踪代码!

com.android.systemui.toast.ToastUI

    @Override
    @MainThread
    public void showToast(int uid, String packageName, IBinder token, CharSequence text,
            IBinder windowToken, int duration, @Nullable ITransientNotificationCallback callback) {
        .........
        mPresenter = new ToastPresenter(context, mAccessibilityManager, mNotificationManager,
                packageName);
        mPresenter.show(view, token, windowToken, duration, mGravity, 0, mY, 0, 0, mCallback);
    }

    @Override
    @MainThread
    public void hideToast(String packageName, IBinder token) {
        if (mPresenter == null || !Objects.equals(mPresenter.getPackageName(), packageName)
                || !Objects.equals(mPresenter.getToken(), token)) {
            Log.w(TAG, "Attempt to hide non-current toast from package " + packageName);
            return;
        }
        hideCurrentToast();
    }


//systemUI中的toastUI 又重新new了一个ToastPresenter来用于toast的显示

ToastPresenter.java
public void show(View view, IBinder token, IBinder windowToken, int duration, int gravity,
            int xOffset, int yOffset, float horizontalMargin, float verticalMargin,
            @Nullable ITransientNotificationCallback callback) {
        ............
        if (mView.getParent() != null) {
            mWindowManager.removeView(mView);
        }
        try {
            mWindowManager.addView(mView, mParams);
        } catch (WindowManager.BadTokenException e) {
            // Since the notification manager service cancels the token right after it notifies us
            // to cancel the toast there is an inherent race and we may attempt to add a window
            // after the token has been invalidated. Let us hedge against that.
            Log.w(TAG, "Error while attempting to show toast from " + mPackageName, e);
            return;
        }
        ................
    }

//ToastPresenter 是通过 mWindowManager.addView(mView, mParams); 将toast 显示,这个具体实现实在WindowManagerService.java

public int addWindow(Session session, IWindow client, int seq,
            LayoutParams attrs, int viewVisibility, int displayId, Rect outFrame,
            Rect outContentInsets, Rect outStableInsets,
            DisplayCutout.ParcelableWrapper outDisplayCutout, InputChannel outInputChannel,
            InsetsState outInsetsState, InsetsSourceControl[] outActiveControls,
            int requestUserId) {
        ................
        synchronized (mGlobalLock) {
            if (!mDisplayReady) {
                throw new IllegalStateException("Display has not been initialialized");
            }

            final DisplayContent displayContent = getDisplayContentOrCreate(displayId, attrs.token);

            if (displayContent == null) {
                ProtoLog.w(WM_ERROR, "Attempted to add window to a display that does "
                        + "not exist: %d. Aborting.", displayId);
                return WindowManagerGlobal.ADD_INVALID_DISPLAY;
            }
            //关键代码
            if (!displayContent.hasAccess(session.mUid)) {
                ProtoLog.w(WM_ERROR,
                        "Attempted to add window to a display for which the application "
                                + "does not have access: %d.  Aborting.", displayId);
                return WindowManagerGlobal.ADD_INVALID_DISPLAY;
            }
            //报错日志发源地....

            if (mWindowMap.containsKey(client.asBinder())) {
                ProtoLog.w(WM_ERROR, "Window %s is already added", client);
                return WindowManagerGlobal.ADD_DUPLICATE_ADD;
            }
            .................
    }


跳转到DisplayContent.java
    /**
     * Returns true if the specified UID has access to this display.
     * 如果指定的UID可以访问此显示,返回true,而bug中的toast不是默认的display显示,
     * 而是在另外的display,所以返回false, !false == true,就报错 return WindowManagerGlobal.ADD_INVALID_DISPLAY
     */
    boolean hasAccess(int uid) {
        return mDisplay.hasAccess(uid);
    }

最后代码执行到ViewRootImpl.java中的setView(xxx)
 /**
     * We have one child
     */
    public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView,
            int userId) {
            .......
            int res; /* = WindowManagerImpl.ADD_OKAY; */

            if (DEBUG_LAYOUT) Log.v(mTag, "Added window " + mWindow);
                if (res < WindowManagerGlobal.ADD_OKAY) {
                    mAttachInfo.mRootView = null;
                    mAdded = false;
                    mFallbackEventHandler.setView(null);
                    unscheduleTraversals();
                    setAccessibilityFocus(null, null);
                    switch (res) {
                        ..................
                        case WindowManagerGlobal.ADD_INVALID_DISPLAY:
                            throw new WindowManager.InvalidDisplayException("Unable to add window "
                                    + mWindow + " -- the specified display can not be found");
                        ..................
                    }
                    throw new RuntimeException(
                            "Unable to add window -- unknown error code " + res);
                }
            ..........

    }


    

看完整个代码流程,有两个方法可以尝试:
方法一:

在ToastPresenter.java 中的show()方法去再次try catch WindowManager.InvalidDisplayException 整个异常,
这样systemUI不会崩溃,但是分屏中的应用的toast不显示
    try {
            ...............
        } catch (WindowManager.BadTokenException e) {
            ............
            Log.w(TAG, "Error while attempting to show toast from " + mPackageName, e);
            return;
        }catch (WindowManager.InvalidDisplayException e){
            Log.w(TAG, "InvalidDisplayException->Error while attempting to show toast from" + mPackageName, e);
            return;
        }

方法二:

DisplayContent.java 中的hasAccess()方法,多添加一个判断,让它在mDisplayId不同的时候返回true

boolean hasAccess(int uid) {
        //add
            if(!isDefaultDisplay){
                return diffDisplay();
            }
         //end
        return mDisplay.hasAccess(uid);
    }
    
private boolean diffDisplay() {
        if (mDisplayId != DEFAULT_DISPLAY) {
            return true;
        }
        return false;
    }

参考链接