美文网首页
从安卓4到最新安卓的通用判断悬浮窗权限

从安卓4到最新安卓的通用判断悬浮窗权限

作者: C_237a | 来源:发表于2020-02-17 10:02 被阅读0次
    /**
     * 判断悬浮窗权限
     */
    public static boolean ifops(Context context) {
        boolean canDraw = false;
        if (Build.VERSION.SDK_INT >= 23) {
            canDraw = Settings.canDrawOverlays(context);
            return canDraw;
        } else if (Build.VERSION.SDK_INT < 19) {
            canDraw = true;
        }
        if (!canDraw && Build.VERSION.SDK_INT >= 19) {
            AppOpsManager appOpsMgr = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
            if (appOpsMgr == null) {
                return true;
            } else {
                try {
                    Class cls = Class.forName("android.content.Context");
                    Field declaredField = cls.getDeclaredField("APP_OPS_SERVICE");
                    declaredField.setAccessible(true);
                    Object obj = declaredField.get(cls);
                    if (!(obj instanceof String)) {
                        return false;
                    }
                    String str2 = (String) obj;
                    obj = cls.getMethod("getSystemService", String.class).invoke(context, str2);
                    cls = Class.forName("android.app.AppOpsManager");
                    Field declaredField2 = cls.getDeclaredField("MODE_ALLOWED");
                    declaredField2.setAccessible(true);
                    Method checkOp = cls.getMethod("checkOp", Integer.TYPE, Integer.TYPE, String.class);
                    int result = (Integer) checkOp.invoke(obj, 24, Binder.getCallingUid(), context.getPackageName());
                    return result == declaredField2.getInt(cls);
                } catch (Exception e) {
                    return false;
                }
            }
        }
        return canDraw;
    }

返回一个boolean
另外提醒一下跳转到打开悬浮窗页面的方法安卓5和之后的并不一样,我先踩为敬

安卓5:

  Intent intent = new Intent();
  intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
  intent.setData(Uri.parse("package:" + this.getPackageName()));
  startActivityForResult(intent, 0);

之后:

        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
        intent.setData(Uri.parse("package:" + getActivity().getPackageName()));
        startActivityForResult(intent, 0);

判断安卓版本懒得写了

相关文章

网友评论

      本文标题:从安卓4到最新安卓的通用判断悬浮窗权限

      本文链接:https://www.haomeiwen.com/subject/xwzvfhtx.html