permission denied for window type 2038 android 10

报错涵义

windows类型2038 android 10的权限被拒绝

在Android 8.0以后对于悬浮窗有了很大的限制,当你想要将视图View加入到WindowManager时,除了在Manifest文件中声明该权限以外:

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

还要保证窗口可以悬浮于其他应用,判断代码如下:

        if (!Settings.canDrawOverlays(this)) {
            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
            startActivity(intent);

找到当前应用,手动授予权限,返回,OK,大功告成。

int type = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ?
                    WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY :
                    WindowManager.LayoutParams.TYPE_PHONE;
WindowManager mWm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                    WindowManager.LayoutParams.WRAP_CONTENT,
                    WindowManager.LayoutParams.WRAP_CONTENT,
                    type,
                    WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                            | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
                            | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                            | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
                            | WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
                    PixelFormat.TRANSLUCENT);
params.format = PixelFormat.RGBA_8888;
params.gravity = Gravity.TOP | Gravity.CENTER_VERTICAL;
  •