WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY 我需要 android.permission.SYSTEM_ALERT_WINDOW 吗?

Do i need android.permission.SYSTEM_ALERT_WINDOW for WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY?

我看到:WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY总是与AndroidManifest.xml中的<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />组合在一起。例如 here.

考虑这段代码:

    windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
    surfaceView = new SurfaceView(this);
    WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(
            100, 100,
            WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
            WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
            PixelFormat.TRANSLUCENT
    );
    layoutParams.gravity = Gravity.START | Gravity.TOP;
    windowManager.addView(surfaceView, layoutParams);

我需要此代码 SYSTEM_ALERT_WINDOW 权限吗?

来自 doc 关于 SYSTEM_ALERT_WINDOW:

Allows an app to create windows using the type TYPE_SYSTEM_ALERT, shown on top of all other apps. Very few apps should use this permission; these windows are intended for system-level interaction with the user.

这是关于 TYPE_SYSTEM_ALERT,而不是关于 TYPE_SYSTEM_OVERLAY。嗯?

更新:
行:windowManager.addView(surfaceView, layoutParams);

java.lang.RuntimeException: Unable to create service: android.view.WindowManager$BadTokenException: Unable to add window android.view.ViewRootImpl$W@10dca8ac -- permission denied for this window type

所以可能 <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /> 是必要的。

改变
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAYWindowManager.LayoutParams.TYPE_TOAST.
android.permission.SYSTEM_ALERT_WINDOW 从应用程序设置中删除并且它有效。

启发:here

WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(
            100, 100,
            WindowManager.LayoutParams.TYPE_TOAST,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
            PixelFormat.TRANSLUCENT
);

看来这个方案不需要android:name="android.permission.SYSTEM_ALERT_WINDOW"

更新
LayoutParams.TYPE_TOAST 已从 API 26 中弃用。请改用 LayoutParams.TYPE_APPLICATION_OVERLAY,它需要 android.Manifest.permission#SYSTEM_ALERT_WINDOW 权限 => See more