如何处理某些棉花糖预装设备上未自动授予的SYSTEM_ALERT_WINDOW权限 [英] How to handle SYSTEM_ALERT_WINDOW permission not being auto-granted on some pre-Marshmallow devices

查看:276
本文介绍了如何处理某些棉花糖预装设备上未自动授予的SYSTEM_ALERT_WINDOW权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在收到一些小米设备(例如运行API级别21的Mi 2)的报告,但没有显示叠加层.我的应用定位到API 23.

I've been getting reports of some Xiaomi devices (e.g. Mi 2, running API level 21) not showing overlays. My app targets API 23.

几个 发布关于此内容.看来MIUI设备在安装时没有启用此权限(与其他棉花糖之前的设备不同).

There are several posts out there regarding this. It seems that MIUI devices do not enable this permission at install time (unlike other pre-Marshmallow devices).

不幸的是,Settings.canDrawOverlays()仅在Android 23+上运行.

Unfortunately, Settings.canDrawOverlays() only works on Android 23+.

  1. 检查棉花糖之前是否尚未启用此权限的正确方法是什么?
  2. 是否有意图将用户带到相关的MUIU设置页面?也许:new Intent("android.settings.action.MANAGE_OVERLAY_PERMISSION", packageName),但我没有办法对此进行测试.
  1. What is the correct way to check whether this permission has not yet been enabled pre-Marshmallow?
  2. Is there an Intent to take the user to the relevant MUIU settings page? Maybe: new Intent("android.settings.action.MANAGE_OVERLAY_PERMISSION", packageName) but I have no means to test this.

推荐答案

使用以下方法更安全地检查您是否具有drawOverlays权限:

Checking if you have the drawOverlays permission is safer using this:

@SuppressLint("NewApi")
public static boolean canDrawOverlayViews(Context con){
    if(Build.VERSION.SDK_INT< Build.VERSION_CODES.LOLLIPOP){return true;}
    try { 
        return Settings.canDrawOverlays(con); 
    }
    catch(NoSuchMethodError e){ 
        return canDrawOverlaysUsingReflection(con); 
    }
}


public static boolean canDrawOverlaysUsingReflection(Context context) {

    try {

        AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        Class clazz = AppOpsManager.class;
        Method dispatchMethod = clazz.getMethod("checkOp", new Class[] { int.class, int.class, String.class });
        //AppOpsManager.OP_SYSTEM_ALERT_WINDOW = 24
        int mode = (Integer) dispatchMethod.invoke(manager, new Object[] { 24, Binder.getCallingUid(), context.getApplicationContext().getPackageName() });

        return AppOpsManager.MODE_ALLOWED == mode;

    } catch (Exception e) {  return false;  }

}

自定义ROM可能已更改操作系统,因此Settings.canDrawOverlays()不可用.小米设备在我身上发生了这种情况,应用程序崩溃了.

Custom ROMs can have altered the OS so that that Settings.canDrawOverlays() is not available. This happened to me with Xiaomi devices and the app crashed.

请求权限:

@SuppressLint("InlinedApi")
public static void requestOverlayDrawPermission(Activity act, int requestCode){
    Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + act.getPackageName()));
    act.startActivityForResult(intent, requestCode);

}

这篇关于如何处理某些棉花糖预装设备上未自动授予的SYSTEM_ALERT_WINDOW权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆