Tried to access visual service WindowManager from a non-visual Context

适配Android12时遇到的一个问题,做个记录:

尝试使用WindowManager做一些事情的时候,我们一般会先获取WindowManager的实例,即:

(WindowManager) context.getSystemService(Context.WINDOW_SERVICE);

但是此代码在Android12上(也有可能是Android11就有问题,没进一步确定)却发生报错

错误信息里有这句话:

Tried to access visual service WindowManager from a non-visual Context

大致意思就是:尝试用一个不可见的上下文去访问可见服务。

既然说我们的TinkerApplication不是可见上下文,这个地方又不能拿到Activity的上下文,所以猜想此处拿到可见上下文是不可能的了,但是报错信息中提示

Use an Activity or a Context created with Context#createWindowContext(int, Bundle),
 which are adjusted to the configuration and visual bounds of an area on screen.

即我们可以通过createWindowContext方法来自己创建一个可见上下文。

经过搜索官方文档得到示例

 ...
 final DisplayManager dm = anyContext.getSystemService(DisplayManager.class);
 final Display primaryDisplay = dm.getDisplay(DEFAULT_DISPLAY);
 final Context windowContext = anyContext.createDisplayContext(primaryDisplay)
         .createWindowContext(TYPE_APPLICATION_OVERLAY, null);
 final View overlayView = Inflater.from(windowContext).inflate(someLayoutXml, null);

 // WindowManager.LayoutParams initialization
 ...
 // The types used in addView and createWindowContext must match.
 mParams.type = TYPE_APPLICATION_OVERLAY;
 ...

 windowContext.getSystemService(WindowManager.class).addView(overlayView, mParams);
 

看到最后的getSystemService时感觉有戏,进过改进和测试后,以下代码可解决问题

WindowManager wm;
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.R) {
                DisplayManager dm = context.getSystemService(DisplayManager.class);
                Display primaryDisplay = dm.getDisplay(DEFAULT_DISPLAY);
                Context windowContext = context.createDisplayContext(primaryDisplay)
                        .createWindowContext(TYPE_APPLICATION_OVERLAY, null);
                wm = (WindowManager) windowContext.getSystemService(Context.WINDOW_SERVICE);
            } else {
                wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            }

如此,获取WindowManager后该干嘛干嘛。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值