Android 在最上层添加悬浮View(兼容Android 8.0)

记着在很久以前写Android的时候做一个在最上层悬浮的一个View非常容易,什么权限啊什么的根本没有那么多限制,,但今天试着写了一下发现处处碰壁,出现了各种各样的问题,后来在网上看了一些资料,发现现在在Android 8.0以上需要申请权限了。下面我们来了解一下:

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

这两个必须在AndroidManifest.xml文件中添加,然后我们看如何添加View到顶层WIndow

private WindowManager mManager;
private View mLayout;

//以上是在测试Activity的头定义的两个变量,不用多解释大家应该从后面的代码看出来是做什么用的。

private void addView() {
        WindowManager.LayoutParams mLayoutParams = new WindowManager.LayoutParams();
        mManager = (WindowManager) getApplication().getSystemService(WINDOW_SERVICE);
        mLayout = LayoutInflater.from(getApplication()).inflate(R.layout.fullscreen, null);
        mLayout.findViewById(R.id.button).setOnClickListener(v -> {
            HHDoctor.hangUp();
            mManager.removeView(mLayout);
        });
//        mLayoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mLayoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        }else {
            mLayoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        }

        mLayoutParams.format = PixelFormat.RGBA_8888;
        mLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        mLayoutParams.gravity = Gravity.LEFT | Gravity.TOP;
        mLayoutParams.x = 0;
        mLayoutParams.y = 0;
        mLayoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        mLayoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
        mManager.addView(mLayout, mLayoutParams);
    }

    private void removeView() {
        if (mManager != null && mLayout != null) {
            mManager.removeView(mLayout);
            mLayout = null;
        }
    }

以上两个方法就是添加View到Window和从WIndow移除的部分

说点什么

avatar
  Subscribe  
提醒