关于悬浮窗Settings.canDrawOverlays获取权限是否开通出错

申请权限:

private static final int PermissionRequestCode = 10;
Intent intent = new Intent();
intent.setAction(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
intent.setData(Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, PermissionRequestCode);

获取是否开通:

Handler mHandler;
@Override
protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (mHandler == null){
        mHandler = new Handler(Looper.getMainLooper());
    }
    mHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && requestCode == PermissionRequestCode){
                boolean nOpen = Settings.canDrawOverlays(XXXActivity.this);
                if (nOpen){
                    //开启
                }else {
                    //关闭
                }
                Log.e("PermissionRequest", "open = " + nOpen);
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && requestCode == PermissionRequestCode){
                AppOpsManager appOpsMgr = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
                int mode = appOpsMgr.checkOpNoThrow("android:system_alert_window", android.os.Process.myUid(), getPackageName());
                if (mode == 1 || mode == 0){
                    //权限已开起
                }else if (mode == 2){
                    //权限已关闭
                }
                Log.e("PermissionRequest", "mode = " + mode);
                //此方法不可行,亲测华为8.0手机  未申请状态时  也返回1
            }
        }
    }, 500);
}

根据https://www.jianshu.com/p/2d35c0c7316a所说,获取权限与activity生命周期有关,google的问题?

表示不理解,反正延时0.5秒再获取,就对了。

直接获取的话,得到的结果是仍然没有开通权限。

你可能感兴趣的:(悬浮窗权限,悬浮窗权限)