适配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后该干嘛干嘛。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)