Testing authority
Settings. CanDrawOverlays (aContext) detects whether a floating window view can be added to the current App.
If true is returned, the permission to add floating views has been obtained.
If false is returned, you need to obtain permissions as described below.
Access permissions
SYSTEM_ALERT_WINDOW, which sets the hover window permission, is a special permission in Android.
To obtain permissions, use the following code.
获取权限
private static final int REQUEST_CODE = 1;
private void requestAlertWindowPermission() {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
intent.setData(Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE) {
if (Settings.canDrawOverlays(this)) {
Log.i(LOGTAG, "onActivityResult granted");
}
}
}
添加悬浮窗视图
fun addOverlay() {
val windowManager = getSystemService(Context.WINDOW_SERVICE) as? WindowManager
val params = WindowManager.LayoutParams()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//8.0新特性
params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
} else {
params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
}
params.format = PixelFormat.RGBA_8888;
//设置flags
//设置flags
params.flags =
(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL //设置flags.不可聚焦及不可使用按钮对悬浮窗进行操控.
or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
or WindowManager.LayoutParams.FLAG_FULLSCREEN //窗口被虚拟按键遮挡问题
or WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
//设置flags.不可聚焦及不可使用按钮对悬浮窗进行操控.
//设置窗口坐标参考系
//设置flags.不可聚焦及不可使用按钮对悬浮窗进行操控.
//设置窗口坐标参考系
params.gravity = Gravity.LEFT or Gravity.TOP
params.x = 0
params.y = 0
params.width = 200
params.height = 200
val container = TextView(this)
overlayContainer = container
container.setBackgroundColor(Color.parseColor("#cce8cf"))
windowManager?.addView(container, params)
}