当前位置:主页 > 移动开发 > Android代码 >

Android视频悬浮窗口实现的示例代码

时间:2020-11-20 17:50:58 | 栏目:Android代码 | 点击:

前言

本文例子实现了点击显示悬浮窗口,同时窗口可播放视频,拖动位置,点击关闭及返回 APP 页面,通过例子来讲述悬浮窗口实现原理及细节处理,效果图如下所示:

悬浮窗口.gif

原理

 WindowManagerView 视图进行添加、移除、更新处理;

WindowManager.LayoutParams 对窗口参数进行一系列设置。

实现

首先,需要添加相对应悬浮窗权限:

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

Activity 页面中,需要判断悬浮窗权限是否获取,如果未曾获取,需要跳转系统页,进行对应的授权操作:

public boolean requestOverlayPermission() {
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if (!Settings.canDrawOverlays(this)) {
      Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
      startActivityForResult(intent, REQUEST_OVERLAY_CODE);
      return true;
    } else {
      return false;
    }
  }
  return false;
}

获取权限后,我们可以首先初始化我们要显示的视图,并且设置相对应的事件,这里我们采用了 VideoView 进行简单的视频播放,并且设置悬浮窗关闭及返回前台的操作:

private View initFloatView() {
  View view = View.inflate(this, R.layout.view_floating_window, null);
  // 设置视频封面
  final ImageView mThumb = (ImageView) view.findViewById(R.id.thumb_floating_view);
  Glide.with(this).load(R.drawable.thumb).into(mThumb);
  // 悬浮窗关闭
  view.findViewById(R.id.close_floating_view).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
      mFloatingWindow.dismiss();
    }
  });
  // 返回前台页面
  view.findViewById(R.id.back_floating_view).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
      mFloatingWindow.setTopApp(FloatingWindowActivity.this);
    }
  });
  final VideoView videoView = view.findViewById(R.id.video_view);
  //视频内容设置
 videoView.setVideoPath("https://stream7.iqilu.com/10339/article/202002/18/2fca1c77730e54c7b500573c2437003f.mp4");
  // 视频准备完毕,隐藏正在加载封面,显示视频
  videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
    @Override
    public void onPrepared(MediaPlayer mp) {
      mThumb.setVisibility(View.GONE);
    }
  });
  // 循环播放
  videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
    @Override
    public void onCompletion(MediaPlayer mp) {
      videoView.start();
    }
  });
  // 开始播放视频
  videoView.start();
  return view;
}

通过获取窗口管理 WindowManager ,设置悬浮窗口参数 WindowManager.LayoutParams 后,就可以通过 WindowManageraddView 方法,生成对应视图的悬浮窗口:

public void showFloatingWindowView(Context context, View view) {
  // 悬浮窗显示视图
  mShowView = view;
  // 获取系统窗口管理服务
  mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
  // 悬浮窗口参数设置及返回
  mFloatParams = getParams();
  // 设置窗口触摸移动事件
  mShowView.setOnTouchListener(new FloatViewMoveListener());
  // 悬浮窗生成
  mWindowManager.addView(mShowView, mFloatParams);
}

WindowManager.LayoutParams 参数设置,主要设置悬浮窗口类型为 WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY

private WindowManager.LayoutParams getParams() {
  WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
  //设置悬浮窗口类型
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
  } else {
    layoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
  }
  //设置悬浮窗口属性
  layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
      | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
      | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
      | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR
      | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;
  //设置悬浮窗口透明
  layoutParams.format = PixelFormat.TRANSLUCENT;
  //设置悬浮窗口长宽数据
  layoutParams.width = 600;
  layoutParams.height = 340;
  //设置悬浮窗显示位置
  layoutParams.gravity = Gravity.START | Gravity.TOP;
  layoutParams.x = 100;
  layoutParams.y = 100;
  return layoutParams;
}

窗口触摸移动事件,主要通过获取触摸位置,通过 WindowManagerupdateViewLayout 方法设置悬浮窗口的参数,进行窗口视图位置更新:

private class FloatViewMoveListener implements View.OnTouchListener {

  //开始触控的坐标,移动时的坐标(相对于屏幕左上角的坐标)
  private int mTouchStartX;
  private int mTouchStartY;
  //开始时的坐标和结束时的坐标(相对于自身控件的坐标)
  private int mStartX, mStartY;
  //判断悬浮窗口是否移动,这里做个标记,防止移动后松手触发了点击事件
  private boolean isMove;

  @Override
  public boolean onTouch(View view, MotionEvent motionEvent) {
    int action = motionEvent.getAction();
    int x = (int) motionEvent.getX();
    int y = (int) motionEvent.getY();
    switch (action) {
      case MotionEvent.ACTION_DOWN:
        isMove = false;
        mTouchStartX = (int) motionEvent.getRawX();
        mTouchStartY = (int) motionEvent.getRawY();
        mStartX = x;
        mStartY = y;
        break;
      case MotionEvent.ACTION_MOVE:
        int mTouchCurrentX = (int) motionEvent.getRawX();
        int mTouchCurrentY = (int) motionEvent.getRawY();
        mFloatParams.x += mTouchCurrentX - mTouchStartX;
        mFloatParams.y += mTouchCurrentY - mTouchStartY;
        mWindowManager.updateViewLayout(mShowView, mFloatParams);
        mTouchStartX = mTouchCurrentX;
        mTouchStartY = mTouchCurrentY;
        float deltaX = x - mStartX;
        float deltaY = y - mStartY;
        if (Math.abs(deltaX) >= 5 || Math.abs(deltaY) >= 5) {
          isMove = true;
        }
        break;
      case MotionEvent.ACTION_UP:
        break;
      default:
        break;
    }
    //如果是移动事件不触发OnClick事件,防止移动的时候一放手形成点击事件
    return isMove;
  }
}

关闭悬浮窗,调用 WindowManagerremoveView 方法即可:

public void dismiss() {
  if (mWindowManager != null && mShowView != null) {
    mWindowManager.removeView(mShowView);
  }
}

悬浮窗点击返回前台方法:

public void setTopApp(Context context) {
  //获取ActivityManager
  ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
  //获得当前运行的task(任务)
  List<ActivityManager.RunningTaskInfo> taskInfoList = null;
  if (activityManager != null) {
    taskInfoList = activityManager.getRunningTasks(100);
  }
  if (taskInfoList != null) {
    for (ActivityManager.RunningTaskInfo taskInfo : taskInfoList) {
      //找到本应用的 task,并将它切换到前台
      if (taskInfo.topActivity != null && taskInfo.topActivity.getPackageName().equals(context.getPackageName())) {
        activityManager.moveTaskToFront(taskInfo.id, 0);
        break;
      }
    }
  }
}

关于悬浮窗的一些基本操作到这里就基本结束了,具体的布局内容及操作,欢迎查看具体的源码实现: Github开发记录

您可能感兴趣的文章:

相关文章