需求:项目需要在页面显示一个可以拖动的窗口播放广告视频,视频窗支持手动关闭,支持跳转网页播放,支持暂停/播放/重播功能
关键点:
1.悬浮窗口不向用户获取system_alert_window权限
2.悬浮窗圆角显示
3.悬浮窗自定义关闭,全屏,播放/暂停/重播按键
实现:
1.使用WindowManager创建创建悬浮窗
WindowManager.LayoutParams wmParams = new WindowManager.LayoutParams();
wmParams.type = WindowManager.LayoutParams.TYPE_APPLICATION;
wmParams.format = PixelFormat.RGBA_8888;
wmParams.gravity = Gravity.START | Gravity.TOP;
wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
wmParams.x = 0;
wmParams.y = 0;
wmParams.alpha = 1;
wmParams.width = 360;
wmParams.height = 760;
WindowManager wManager = activity.getWindowManager();
//创建一个View对象,作为悬浮窗的内容
View videoView = LayoutInflater.from(activity).inflate(R.layout.float_videoview, null);
wManager.addView(videoView, wmParams);
2.悬浮窗布局
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/video_view_container"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextureView
android:id="@+id/texture_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"/>
<ImageView
android:id="@+id/close"
android:tag="close"
android:layout_width="16dp"
android:layout_height="16dp"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:visibility="visible"/>
<ImageView
android:id="@+id/fullScreen"
android:tag="fullScreen"
android:layout_width="16dp"
android:layout_height="16dp"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:layout_gravity="right"
android:visibility="visible"/>
<ImageView
android:id="@+id/pause"
android:tag="pause"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_gravity="center"
android:visibility="visible"/>
</FrameLayout>
3.手势移动悬浮窗
videoView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
downTimeMillis = System.currentTimeMillis();
mXDownInScreen = event.getRawX();
mYDownInScreen = event.getRawY();
downX = event.getX();
downY = event.getY();
break;
case MotionEvent.ACTION_MOVE:
moveX = Ma