【问题标题】:Android 'Unable to add window -- token null is not for an application' exception only with TYPE_ACCESSIBILITY_OVERLAYAndroid \'无法添加窗口 -- token null is not for an application\' exception only with TYPE_ACCESSIBILITY_OVERLAY
【发布时间】:2023-01-14 04:10:10
【问题描述】:

我正在尝试创建一个可访问的 HUD,它用半透明颜色覆盖系统。

我有一个调用我的 HUD 类的服务(这是另一个服务)

startService(new Intent(getApplicationContext(), HUD.class));

我的 HUD 服务类:

    @Override
    public void onCreate() {
        super.onCreate();

        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);

        filter = new View(this); 
        float alpha = (float) 0.8; 
        filter.setAlpha(alpha);
        filter.setBackgroundColor(Color.RED);
        filter.getBackground().setAlpha(80); 

        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                -1, // Match parent
                -1, // Match parent
                WindowManager.LayoutParams.TYPE_ACCESSIBILITY_OVERLAY,
                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE |
                        WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH |
                        WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT); 

        params.gravity = Gravity.TOP;
        params.x = 0;
        params.y = 100;

        windowManager.addView(filter, params);
    }

但是,此代码仅在我将 WindowManager.LayoutParams.TYPE_ACCESSIBILITY_OVERLAY 更改为 WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY 时才有效,但这不是我想要的。我收到的错误是:

     Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?

我已经尝试按照多个链接中的建议更改我获取上下文的方式,从 getApplicationContext()MyActivity.this(为此,我将我的 HUD 服务类移动到 Activity 的唯一目的是以不同的方式获取上下文。这仍然给了我同样的崩溃,如果我不将窗口标记为可访问性覆盖,它就会消失。

【问题讨论】:

    标签: java android android-context accessibility


    【解决方案1】:

    你找到解决办法了吗? 现在面临同样的情况。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-26
      • 2017-10-02
      • 1970-01-01
      • 1970-01-01
      • 2019-07-01
      • 2022-10-02
      • 1970-01-01
      相关资源
      最近更新 更多