WindowManager addView 添加报错 异常关于type类型设置

高版本的系统中设置悬浮窗时候

layoutparams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR

会报错:

android.view.WindowManager$BadTokenException: Unable to add window android.view.ViewRootImpl$W@d4c6880 -- permission denied for window type 2003
        at android.view.ViewRootImpl.setView(ViewRootImpl.java:909)
        at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:372)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:136)

解决办法如下:

判断高版本的方法

if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
            layoutparams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
        }else{
            layoutparams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR
        }
1.清单文件权限

2.当然请求权限的时候别忘了版本判断
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(context)) {
                val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
                startActivityForResult(intent, 100)
            }else{
                initWindow()
            }
        }

你可能感兴趣的:(Android用法,windowmanager,悬浮窗)