Android service中弹出dialog 权限变动与用法
专注于Android开发,分享经验总结,欢迎加入
最近在做音视频聊天需要在service中弹出聊天界面,开发期间遇到的坑特此记录(Android9系统)
报错信息有如下:
Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
android.view.WindowManager$BadTokenException Unable to add window android.view.ViewRootImpl$W@fa525bc -- permission denied for window type 2002
permission denied for window type 2003
permission denied for window type 2007
遇到此类信息都是WindowManager.LayoutParams 设置的type不对
这是因为android O(Android8系统)对悬浮窗的设计做了一些修改,在使用android.permission.SYSTEM_ALERT_WINDOW 权限的应用无法再使用以下窗口类型来在其他应用和系统窗口上显示悬浮窗:
WindowManager.LayoutParams.TYPE_PRIORITY_PHONE
WindowManager.LayoutParams.TYPE_PHONE
WindowManager.LayoutParams.TYPE_SYSTEM_ERROR
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY
正确使用如下:在dialog调用show()方法之前设置type
Window window = mAlertDialog.getWindow();
if (window != null) {
WindowManager.LayoutParams attributes = window.getAttributes();
if (attributes != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
attributes.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
} else {
attributes.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
}
}
window.setAttributes(attributes);
}
mAlertDialog.show();
记得在AndroidManifest.xml 写加入权限
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
在Android6.0之后还需动态申请权限
微信公众号 -->> 他晓 (欢迎加入)