0. 现完成功能:
- 悬浮窗区分横屏竖屏两种尺寸
- 悬浮窗可以在页面上随意拖动
- 在播放视频时按返回键/Home键/离开当前页时触发开启
- 悬浮窗显示在退到后台/在应用内/桌面
- 带播放进度开启悬浮窗,带播放进度回到应用内页面
- 权限:每次开启前判断有无权限,没权限并且请求过就不开悬浮窗
已通过现有机型测试:三星、华为、vivo
1.引入依赖
//完整版引入
implementation 'com.shuyu:GSYVideoPlayer:8.1.2'
github:https://github.com/CarGuo/GSYVideoPlayer(强烈建议下载Demo源码,每个方法注释写的很清晰)
踩坑1:部分依赖时 打包apk一播放视频就崩溃,连接真机正常播放。报错是aliplay原因,注释掉换一个播放器内核:
implementation 'com.github.CarGuo.GSYVideoPlayer:gsyVideoPlayer-java:v8.3.4-release-jitpack'
//implementation 'com.github.CarGuo.GSYVideoPlayer:GSYVideoPlayer-aliplay:8.3.4-release-jitpack'
PlayerFactory.setPlayManager(SystemPlayerManager.class); // 换个系统内核
2.清单文件声明悬浮窗权限
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
3.从Demo源码导出需要的15个文件加入自己项目,并进行部分修改
1)修改悬浮窗布局 layout_floating_video,加上删除和回到应用的icon,点击播放/暂停的区域
layout_floating_video.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/surface_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
</FrameLayout>
<LinearLayout
android:id="@+id/ll_center"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:gravity="center">
<moe.codeest.enviews.ENPlayView
android:id="@+id/start"
android:layout_width="35dp"
android:layout_height="35dp" />
</LinearLayout>
<ImageView
android:id="@+id/iv_delete"
android:layout_width="38dp"
android:layout_height="38dp"
android:layout_alignParentLeft="true"
android:padding="9dp"
android:src="@drawable/video_small_close" />
<ImageView
android:id="@+id/iv_detail"
android:layout_width="38dp"
android:layout_height="38dp"
android:layout_alignParentRight="true"
android:padding="12dp"
android:src="@drawable/video_enlarge" />
</RelativeLayout>
FloatingVideo.java
public class FloatingVideo extends StandardGSYVideoPlayer {
//... 以下新添
//用于跳转回对应页面
public int newsId;
private NewsDetailActivity activity;
public FloatingVideo(Context context, int newsId, LaunchActivity activity){
super(context);
this.newsId = newsId;
this.activity = activity;
}
@Override
protected void init(Context context) {
//...
//mStartButton.setOnClickListener(new OnClickListener() {
// @Override
// public void onClick(View v) {
// clickStartIcon();
// }
//});
//播放/暂停
LinearLayout llCenter = findViewById(R.id.ll_center);
llCenter.setOnClickListener(v -> clickStartIcon());
//关闭
ImageView ivDelete = findViewById(R.id.iv_delete);
ivDelete.setOnClickListener(view -> {
GSYVideoManager.instance().releaseMediaPlayer();
FloatWindow.destroy();
});
//去详情
ImageView ivDetail = findViewById(R.id.iv_detail);
ivDetail.setOnClickListener(view -> {
if(mContext!=null && newsId!=0){
Long progress = getGSYVideoManager().getCurrentPosition();
Bundle bundle = new Bundle();
bundle.putInt("news_id", newsId);
if(activity != null){
activity.startActivity(new NewsDetailActivity(bundle))
setTopApp(context);
}
GSYVideoManager.instance().releaseMediaPlayer();
FloatWindow.destroy();
}
});
}
//当本应用位于后台时,则将它切换到最前端
public static void setTopApp(Context context) {
if (isRunningForeground(context)) {
return;
}
//获取ActivityManager
ActivityManager activityManager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
//获得当前运行的task(任务)
List<ActivityManager.RunningTaskInfo> taskInfoList = activityManager.getRunningTasks(100);
for (ActivityManager.RunningTaskInfo taskInfo : taskInfoList) {
//找到本应用的 task,并将它切换到前台
if (taskInfo.topActivity.getPackageName().equals(context.getPackageName())) {
activityManager.moveTaskToFront(taskInfo.id, 0);
break;
}
}
}
//判断本应用是否已经位于最前端:已经位于最前端时,返回 true;否则返回 false
public static boolean isRunningForeground(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> appProcessInfoList = activityManager.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo appProcessInfo : appProcessInfoList) {
if (appProcessInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
&& appProcessInfo.processName.equals(context.getApplicationInfo().processName)) {
return true;
}
}
return false;
}
}
2)悬浮窗接收参数:播放进度和数据源
FloatPlayerViewjava
public class FloatPlayerView extends FrameLayout {
//... 以下新添
public FloatPlayerView(Context context, Bundle bundle, LaunchActivity activity) {
super(context);
init(bundle,activity);
}
private void init(Bundle bundle, LaunchActivity activity) {
if(bundle == null) return;
videoPlayer = new FloatingVideo(getContext(), (int) bundle.get("vNewsId"),activity);
LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.gravity = Gravity.CENTER;
addView(videoPlayer, layoutParams);
//设置播放源
videoPlayer.setUp((String) bundle.get("vSource"), true, "");
//设置播放进度
videoPlayer.setSeekOnStart((Long) bundle.get("vPosition"));
//是否可以滑动调整
videoPlayer.setIsTouchWiget(false);
//开始播放
videoPlayer.startPlayLogic();
}
3)解决bug:拒绝权限还存在视频声音
FloatPhone.java
class FloatPhone extends FloatView {
//...
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void init() {
if (Util.hasPermission(mContext)) {//...
} else {
FloatVideoActivity.request(mContext, new PermissionListener() {//...
@Override
public void onFail() {
//就这行
GSYVideoManager.instance().releaseMediaPlayer();
}
});
}
}
@Override
public void dismiss() {
//捕获异常
try{
mWindowManager.removeView(mView);
}catch (Exception e){
Log.e("FloatWindow",e.getMessage());
}
}
}
4. 播放视频&开启悬浮窗
XxxActivity.java 自己的页面文章来源:https://www.toymoban.com/news/detail-410528.html
//视频
private OrientationUtils orientationUtils;
private long floatProgress;
private FloatPlayerView floatPlayerView;
//准备视频播放器:请求完数据后调用
private synchronized void prepareVideo() {
//关掉悬浮窗
if (FloatWindow.get() != null) {
FloatWindow.destroy();
}
videoPlayer.setVisibility(View.VISIBLE);
//设置内核
PlayerFactory.setPlayManager(SystemPlayerManager.class);
//设置代理缓存模式
CacheFactory.setCacheManager(ProxyCacheManager.class);
//封面
ImageView imageView = new ImageView(getContext());
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
Glide.with(getContext()).load(newsBean.getVideo()).dontAnimate().into(imageView);
videoPlayer.setThumbImageView(imageView);
//隐藏返回键和标题
videoPlayer.getTitleTextView().setVisibility(View.GONE);
videoPlayer.getBackButton().setVisibility(View.GONE);
videoPlayer.setUp(newsBean.getVideo(), true, "");
//旋转
orientationUtils = new OrientationUtils(getParentActivity(), videoPlayer);
//全屏按键功能,这是使用的是选择屏幕,而不是全屏
videoPlayer.getFullscreenButton().setOnClickListener(v -> {
//旋转屏幕
orientationUtils.resolveByClick();
videoPlayer.startWindowFullscreen(getContext(), false, true);
});
//是否可以滑动调整
videoPlayer.setIsTouchWiget(true);
videoPlayer.setNeedLockFull(true);
videoPlayer.setAutoFullWithSize(true);
//拖到已有进度播放
if (floatProgress > 0)
videoPlayer.setSeekOnStart(floatProgress);
}
}
//init :onCreate调用
private void initDataNewsDetail() {
//和小窗同一条新闻 -> 读取进度 不同新闻 -> 关小窗
if (FloatWindow.get() != null && FloatWindow.newsId == newsId) {
if (FloatWindow.get().getView() != null) {
floatProgress = ((FloatPlayerView) FloatWindow.get().getView()).getVideoPlayer().getGSYVideoManager().getCurrentPosition();
}
FloatWindow.destroy();
}
presenter.getDetail(newsId);
}
//开启悬浮窗
private void openFloatVideo() {
if (orientationUtils != null) {
orientationUtils.backToProtVideo();
}
//记录有没有请求过
boolean isFirstRePermission = SPUtils.getInstance().get("is_first_request_window",true);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
//没权限并且请求过 就pass不开悬浮窗
if(!Util.hasPermission(getContext()) && !isFirstRePermission){
getCurPlay().onVideoPause();
return;
}
}
if(isFirstRePermission){
SPUtils.getInstance().save("is_first_request_window",false);
}
if (!GSYVideoManager.backFromWindowFull(getContext())) {
if (FloatWindow.get() == null && videoPlayer.getCurrentPlayer().getCurrentState() == CURRENT_STATE_PLAYING && !TextUtils.isEmpty(newsBean.getVideo())) {
videoPlayer.onVideoPause();
FloatWindow.newsId = newsId;
long position = videoPlayer.getGSYVideoManager().getCurrentPosition();
Bundle bundle = new Bundle();
//传参给悬浮窗
bundle.putString("vSource", newsBean.getVideo());
bundle.putLong("vPosition", position);
bundle.putInt("vNewsId", newsBean.getId());
floatPlayerView = new FloatPlayerView(getParentActivity().getApplicationContext(), bundle, (LaunchActivity) getParentActivity());
//悬浮窗比例
float ratio = 0.55f;//横屏
FloatingVideo floatingVideo = floatPlayerView.getVideoPlayer();
floatingVideo.setAutoFullWithSize(true);
if(floatingVideo.isVerticalFullByVideoSize()){
ratio = 0.3f;//竖屏
}
FloatWindow
.with(getParentActivity().getApplicationContext())
.setView(floatPlayerView)
.setWidth(Screen.width, ratio)
.setHeight(Screen.width, (float)floatingVideo.getCurrentVideoHeight()/(float)floatingVideo.getCurrentVideoWidth() * ratio)
.setX(Screen.width, 0.8f)
.setY(Screen.height, 0.3f)
.setMoveType(MoveType.slide)
.setFilter(false)
.setMoveStyle(500, new BounceInterpolator())
.build();
FloatWindow.get().show();
}
}
}
若出现未考虑的情况或其他bug,欢迎评论补充。文章来源地址https://www.toymoban.com/news/detail-410528.html
到了这里,关于Android - 使用GSY实现视频播放和画中画悬浮窗的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!