最近用了一个很好用的开源库,在APP全局或部分页面显示悬浮框,例如音乐播放的歌词显示等。下面我将记录下简单使用笔记。
1.在清单文件添加悬浮框权限
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
2.判断是否有悬浮框的权限
if (Build.VERSION.SDK_INT >= 23) {
if (!Settings.canDrawOverlays(this)) {
//若未授权则请求权限
ToastUitls.showShort("请允许悬浮窗权限");
getOverlayPermission();
}
}
3.跳转到设置页面开启悬浮框权限
//请求悬浮窗权限
@TargetApi(Build.VERSION_CODES.M)
private void getOverlayPermission() {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
intent.setData(Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, 0);
}
4.添加依赖
implementation 'com.github.yhaolpz:FloatWindow:1.0.9'
5.初始化悬浮框控件
if (FloatWindow.get() == null) {
View view = LayoutInflater.from(this).inflate(R.layout.view_audio_float, null);
int width = CommonUtils.dp2px(this, CommonUtils.px2dp(this, getScreenWidth()) - 20);
FloatWindow
.with(MyApp.getAppContext())
.setView(view)
.setWidth(width) //设置控件宽高
.setHeight(height)
.setX(CommonUtils.dp2px(this, 10)) //设置控件初始位置
.setY(startY)
.setDesktopShow(true)//桌面是否显示
.setMoveType(MoveType.inactive)
.setFilter(false, SplashActivity.class)//app中不显示的页面
.build();
}
6.显示悬浮框
if (FloatWindow.get() != null) {
FloatWindow.get().show();
}
7.更新悬浮框X/Y的位置
FloatWindow.get().updateY(startY);
FloatWindow.get().updateX(startX);
8.关闭或隐藏
FloatWindow.get().hide();//仅隐藏
FloatWindow.get().destroy();//销毁
最后,附上开源库的连接,感谢致力于开源代码开发的大神们