悬浮窗功能基本代码:
//创建悬浮窗的图片,这里当然也可以用自定义的View,这里之用了简单的图片
var imageView = ImageView(this)
imageView.setImageResource(R.mipmap.ic_launcher)
var layoutParams = WindowManager.LayoutParams()
var windowManager: WindowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
layoutParams.format = PixelFormat.RGBA_8888
layoutParams.flags =
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
layoutParams.gravity = Gravity.TOP or Gravity.LEFT
layoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT
layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT
layoutParams.x = 200
layoutParams.y = 200
windowManager.addView(imageView, layoutParams)
如果有报错,那可能是没有设置悬浮窗的类型的原因。
只要在windowManager.addView 之前添加悬浮窗类型的代码即可
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION
} else
layoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT
当然,有的需求可能不太满足,比如说我想要在桌面也显示的话怎么办?
那就得需要用户自己到应用设置里面去打开后台弹出界面了。
layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
var intent = Intent()
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
//跳转到应用信息界面
intent.action = Intent.ACTION_AUTO_REVOKE_PERMISSIONS
//跳转到哪个应用的信息界面
intent.data = Uri.fromParts("package", packageName, null)
startActivity(intent)
悬浮窗暂时只写这么多,如果后面还有的话我还是会补充的。
有问题的话可直接评论。



