作者

大家好,我叫小鑫,也能够叫我蜡笔小鑫;

本人17年结业于中山大学,于2018年7月参加37手游安卓团队,从前就职于久邦数码担任安卓开发工程师;

现在是37手游安卓团队的海外担任人,担任相关事务开发;同时统筹一些基础建设相关工作。

布景

游戏内的悬浮窗一般情况下只出现在游戏内,用做切换账号、客服中心等功能的快速入口。本文将介绍几种完成计划,以及咱们踩过的坑

1、计划一:运用外悬浮窗+栈顶权限/生命周期回调

一般完成悬浮窗,首要考虑到的会是要运用悬浮窗权限,用WindowManager在设备界面上addView完成(UI层级较高,运用外显现)

1、弹出悬浮窗需求用到悬浮窗权限

    <!--悬浮窗权限-->
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

2、判断悬浮窗游戏内外显现

方式一:运用栈顶权限获取当时

//需求声明权限
<uses-permission android:name="android.permission.GET_TASKS" />
//判断当时是否在后台
private boolean isAppIsInBackground(Context context) {
		boolean isInBackground = true;
		ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
			List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
			for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
				//前台程序
				if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
					for (String activeProcess : processInfo.pkgList) {
						if (activeProcess.equals(context.getPackageName())) {
							isInBackground = false;
						}
					}
				}
			}
		} else {
			List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
			ComponentName componentInfo = taskInfo.get(0).topActivity;
			if (componentInfo.getPackageName().equals(context.getPackageName())) {
				isInBackground = false;
			}
		}
		return isInBackground;
	}

这里考虑到这种计划网上有许多详细事例,在这里就不完成了。可是这种计划有如下缺点:

1、适配问题,悬浮窗权限在不同设备上因为不同产商完成不同,适配难。

2、向用户申请权限,翻开率较低,体会较差

2、计划二:addContentView完成

原理:Activity的接口中除了咱们常用的setContentView接口外,还有addContentView接口。运用该接口能够在Activity上添加View。

这里你可能会问:

1、那只能在一个Activity上添加吧?

没错,是只能在当时Activity上添加,可是因为游戏一般也就在一个Activity跑,因而基本上是能够接受的。

2、只add一个view,那拖动怎么完成?

LayoutParams params = new LayoutParams(mWidth, mHeight);
params.setMargins(mLeft, mTop, 0, 0);
setLayoutParams(params);

通过更新LayoutParams调整子View在父View中的方位就能完成

详细代码如下:

/**
 * @author zhuxiaoxin
 * 可拖拽贴边的view
 */
public class DragViewLayout extends RelativeLayout {
    //手指拖拽得到的方位
    int mLeft, mRight, mTop, mBottom;
    //view所在的方位
    int mLastX, mLastY;
    /**
     * 屏幕宽度|高度
     */
    int mScreenWidth, mScreenHeight;
    /**
     * view的宽度|高度
     */
    int mWidth, mHeight;
    /**
     * 是否在拖拽过程中
     */
    boolean isDrag = false;
    /**
     * 体系最小滑动间隔
     * @param context
     */
    int mTouchSlop = 0;
    public DragViewLayout(Context context) {
        this(context, null);
    }
    public DragViewLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }
    public DragViewLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mScreenWidth = context.getResources().getDisplayMetrics().widthPixels;
        mScreenHeight = context.getResources().getDisplayMetrics().heightPixels;
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
    }
    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
    }
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        int action = event.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                mLeft = getLeft();
                mRight = getRight();
                mTop = getTop();
                mBottom = getBottom();
                mLastX = (int) event.getRawX();
                mLastY = (int) event.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                int x = (int) event.getRawX();
                int y = (int) event.getRawY();
                int dx = x - mLastX;
                int dy = y - mLastY;
                if (Math.abs(dx) > mTouchSlop) {
                    isDrag = true;
                }
                mLeft += dx;
                mRight += dx;
                mTop += dy;
                mBottom += dy;
                if (mLeft < 0) {
                    mLeft = 0;
                    mRight = mWidth;
                }
                if (mRight >= mScreenWidth) {
                    mRight = mScreenWidth;
                    mLeft = mScreenWidth - mWidth;
                }
                if (mTop < 0) {
                    mTop = 0;
                    mBottom = getHeight();
                }
                if (mBottom > mScreenHeight) {
                    mBottom = mScreenHeight;
                    mTop = mScreenHeight - mHeight;
                }
                mLastX = x;
                mLastY = y;
                //依据拖动举例设置view的margin参数,完成拖动效
                LayoutParams params = new LayoutParams(mWidth, mHeight);
                params.setMargins(mLeft, mTop, 0, 0);
                setLayoutParams(params);
                break;
            case MotionEvent.ACTION_UP:
                //手指抬起,履行贴边动画
                if (isDrag) {
                    startAnim();
                    isDrag = false;
                }
                break;
        }
        return super.dispatchTouchEvent(event);
    }
    //履行贴边动画
    private void startAnim(){
        ValueAnimator valueAnimator;
        if (mLeft < mScreenWidth / 2) {
            valueAnimator = ValueAnimator.ofInt(mLeft, 0);
        } else {
            valueAnimator = ValueAnimator.ofInt(mLeft, mScreenWidth - mWidth);
        }
        //动画履行时间
        valueAnimator.setDuration(100);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mLeft = (int)animation.getAnimatedValue();
                //动画履行依然是运用设置margin参数完成
                LayoutParams params = new LayoutParams(mWidth, mHeight);
                params.setMargins(mLeft, getTop(), 0, 0);
                setLayoutParams(params);
            }
        });
        valueAnimator.start();
    }
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if (mWidth == 0) {
            //获取view的高宽
            mWidth = getWidth();
            mHeight = getHeight();
        }
    }
}
/**
 * @author zhuxiaoxin
 * 37悬浮窗基础view
 */
public class SqAddFloatView extends DragViewLayout {
    private RelativeLayout mFloatContainer;
    public SqAddFloatView(final Context context, final int floatImgId) {
        super(context);
        setClickable(true);
        final ImageView floatView = new ImageView(context);
        floatView.setImageResource(floatImgId);
        floatView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(context, "点击了悬浮球", Toast.LENGTH_SHORT).show();
            }
        });
        LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        addView(floatView, params);
    }
    public void show(Activity activity) {
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
        if(mFloatContainer == null) {
            mFloatContainer = new RelativeLayout(activity);
        }
        RelativeLayout.LayoutParams floatViewParams = new RelativeLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
        floatViewParams.setMargins(0, (int) (mScreenHeight * 0.4), 0, 0);
        mFloatContainer.addView(this, floatViewParams);
        activity.addContentView(mFloatContainer, params);
    }
}

在Activity中运用

SqAddFloatView(this, R.mipmap.ic_launcher).show(this)

3、计划三:WindowManager+运用内层级完成

WindowManger中的层级有如下两个(其实是一样的~)能够完成在Activity上添加View

        /**
         * Start of types of sub-windows.  The {@link #token} of these windows
         * must be set to the window they are attached to.  These types of
         * windows are kept next to their attached window in Z-order, and their
         * coordinate space is relative to their attached window.
         */
        public static final int FIRST_SUB_WINDOW = 1000;
        /**
         * Window type: a panel on top of an application window.  These windows
         * appear on top of their attached window.
         */
        public static final int TYPE_APPLICATION_PANEL = FIRST_SUB_WINDOW;

详细完成时,WindowManger相关的中心代码如下:

    public void show() {
        floatLayoutParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT, 
//最最重要的一句                                                           WindowManager.LayoutParams.FIRST_SUB_WINDOW,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                        | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
                PixelFormat.RGBA_8888);
        floatLayoutParams.gravity = Gravity.LEFT | Gravity.TOP;
        floatLayoutParams.x = mMinWidth;
        floatLayoutParams.y = (int)(mScreenHeight * 0.4);
        mWindowManager.addView(this, floatLayoutParams);
    }

添加完view怎么更新方位?

运用WindowManager的updateViewLayout办法

mWindowManager.updateViewLayout(DragViewLayout.this, floatLayoutParams);

完好代码如下:

DragViewLayout:

public class DragViewLayout extends RelativeLayout {
    //view所在方位
    int mLastX, mLastY;
    //屏幕高宽
    int mScreenWidth, mScreenHeight;
    //view高宽
    int mWidth, mHeight;
    /**
     * 是否在拖拽过程中
     */
    boolean isDrag = false;
    /**
     * 体系最小滑动间隔
     * @param context
     */
    int mTouchSlop = 0;
    WindowManager.LayoutParams floatLayoutParams;
    WindowManager mWindowManager;
    //手指接触方位
    private float xInScreen;
    private float yInScreen;
    private float xInView;
    public float yInView;
    public DragViewLayout(Context context) {
        this(context, null);
    }
    public DragViewLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }
    public DragViewLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mScreenWidth = context.getResources().getDisplayMetrics().widthPixels;
        mScreenHeight = context.getResources().getDisplayMetrics().heightPixels;
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
        mWindowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
    }
    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
    }
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        int action = event.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                mLastX = (int) event.getRawX();
                mLastY = (int) event.getRawY();
                yInView = event.getY();
                xInView = event.getX();
                xInScreen = event.getRawX();
                yInScreen = event.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                int dx = (int) event.getRawX() - mLastX;
                int dy = (int) event.getRawY() - mLastY;
                if (Math.abs(dx) > mTouchSlop || Math.abs(dy) > mTouchSlop) {
                    isDrag = true;
                }
                xInScreen = event.getRawX();
                yInScreen = event.getRawY();
                mLastX = (int) event.getRawX();
                mLastY = (int) event.getRawY();
                //拖拽时调用WindowManager updateViewLayout更新悬浮球方位
                updateFloatPosition(false);
                break;
            case MotionEvent.ACTION_UP:
                if (isDrag) {
                    //履行贴边
                    startAnim();
                    isDrag = false;
                }
                break;
            default:
                break;
        }
        return super.dispatchTouchEvent(event);
    }
    //更新悬浮球方位
    private void updateFloatPosition(boolean isUp) {
        int x = (int) (xInScreen - xInView);
        int y = (int) (yInScreen - yInView);
        if(isUp) {
            x = isRightFloat() ? mScreenWidth : 0;
        }
        if(y < 0) {
            y = 0;
        }
        if(y > mScreenHeight - mHeight) {
            y = mScreenHeight - mHeight;
        }
        floatLayoutParams.x = x;
        floatLayoutParams.y = y;
        //更新方位
        mWindowManager.updateViewLayout(this, floatLayoutParams);
    }
    /**
     * 是否靠右边悬浮
     * @return
     */
    boolean isRightFloat() {
        return xInScreen > mScreenWidth / 2;
    }
    //履行贴边动画
    private void startAnim(){
        ValueAnimator valueAnimator;
        if (floatLayoutParams.x < mScreenWidth / 2) {
            valueAnimator = ValueAnimator.ofInt(floatLayoutParams.x, 0);
        } else {
            valueAnimator = ValueAnimator.ofInt(floatLayoutParams.x, mScreenWidth - mWidth);
        }
        valueAnimator.setDuration(200);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                floatLayoutParams.x = (int)animation.getAnimatedValue();
                mWindowManager.updateViewLayout(DragViewLayout.this, floatLayoutParams);
            }
        });
        valueAnimator.start();
    }
    //悬浮球显现
    public void show() {
        floatLayoutParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.FIRST_SUB_WINDOW,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                        | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
                PixelFormat.RGBA_8888);
        floatLayoutParams.gravity = Gravity.LEFT | Gravity.TOP;
        floatLayoutParams.x = 0;
        floatLayoutParams.y = (int)(mScreenHeight * 0.4);
        mWindowManager.addView(this, floatLayoutParams);
    }
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if (mWidth == 0) {
            //获取悬浮球高宽
            mWidth = getWidth();
            mHeight = getHeight();
        }
    }
}

悬浮窗View

public class SqWindowManagerFloatView extends DragViewLayout {
    public SqWindowManagerFloatView(final Context context, final int floatImgId) {
        super(context);
        setClickable(true);
        final ImageView floatView = new ImageView(context);
        floatView.setImageResource(floatImgId);
        floatView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(context, "点击了悬浮球", Toast.LENGTH_SHORT).show();
            }
        });
        LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        addView(floatView, params);
    }
}

运用:

SqWindowManagerFloatView(this, R.mipmap.float_icon).show()

4、小结

1、计划一需求用到多个权限,显然是不合适的。

2、计划二简单便利,可是用到了Activity的addContentView办法,在某些游戏引擎上运用会有问题。因为有些游戏引擎不是在Activity上跑的,而是在NativeActivity上跑

3、计划三是咱们当时选用的计划,现在还暂未发现有显现不出来之类的问题~

4、本文讲述的计划只是Demo哈,实际运用还需求考虑刘海屏的问题,本文暂未涉及