一般在service中弹出全局dialog因为权限,版本等原因出现下面这个错误
2021-08-29 11:48:06.023 32312-32312/com.example.myapplication2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication2, PID: 32312
android.view.WindowManager$BadTokenException: Unable to add window android.view.ViewRootImpl$W@c7939b1 -- permission denied for window type 2038
at android.view.ViewRootImpl.setView(ViewRootImpl.java:738)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:353)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:94)
at android.app.Dialog.show(Dialog.java:345)
at com.example.myapplication2.MyService$1.handleMessage(MyService.java:66)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6435)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:939)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:829)
解决方案就是动态判断是否开启悬浮窗权限,如果没有就跳到对应页面开启悬浮窗权限 这部分参考链接 https://blog.csdn.net/aidou1314/article/details/88422007?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-1.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-1.control 如果获取到权限还是报错,在showDialog之前加上版本判断
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
}else {
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
}
亲测适用所有版本
|