}, 1000)
}
}
}
}
override fun onRestart() {
super.onRestart()
Log.d(“RemoteView”, “重新显示了”)
//不显示悬浮框
if (hasBind) {
unbindService(mVideoServiceConnection)
hasBind = false
}
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
}
override fun onDestroy() {
super.onDestroy()
}
}
- 新建悬浮窗Service
新建悬浮窗Service FloatWinfowServices,因为我们使用的BindService,我们在onBind方法中初始化service中的布局
override fun onBind(intent: Intent): IBinder? {
initWindow()
//悬浮框点击事件的处理
initFloating()
return MyBinder()
}
service中我们通过WindowManager来添加一个布局显示。
/**
- 初始化窗口
*/
private fun initWindow() {
winManager = application.getSystemService(Context.WINDOW_SERVICE) as WindowManager
//设置好悬浮窗的参数
wmParams = params
// 悬浮窗默认显示以左上角为起始坐标
wmParams!!.gravity = Gravity.LEFT or Gravity.TOP
//悬浮窗的开始位置,因为设置的是从左上角开始,所以屏幕左上角是x=0;y=0
wmParams!!.x = winManager!!.defaultDisplay.width
wmParams!!.y = 210
//得到容器,通过这个inflater来获得悬浮窗控件
inflater = LayoutInflater.from(applicationContext)
// 获取浮动窗口视图所在布局
mFloatingLayout = inflater!!.inflate(R.layout.remoteview, null)
// 添加悬浮窗的视图
winManager!!.addView(mFloatingLayout, wmParams)
}
悬浮窗的参数主要设置悬浮窗的类型为
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
8.0 以下可设置为:
wmParams!!.type = WindowManager.LayoutParams.TYPE_PHONE
代码如下所示:
private //设置window type 下面变量2002是在屏幕区域显示,2003则可以显示在状态栏之上
//设置可以显示在状态栏上
//设置悬浮窗口长宽数据
val params: WindowManager.LayoutParams
get() {
wmParams = WindowManager.LayoutParams()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
wmParams!!.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
} else {
wmParams!!.type = WindowManager.LayoutParams.TYPE_PHONE
}
wmParams!!.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN or WindowManager.LayoutParams.FLAG_LAYOUT_INSET_