android AppOpsManager 检查应用权限

AppOpsManager 介绍

AppOpsManager 是其他模块获取应用程序的操作(权限)的管理类,核心实现类为AppOpsService,由AppOpsManager对外提供可使用的API,其基本工作框架为:
appops 工作原理框架
AppOpsManager是Android 4.3开始谷歌将权限管理功能集成系统里而提供的外部类,所以对于低于4.3版本将不提供该类的实现。

通过反射AppOpsManager检查应用权限

下面提供的方法通过反射使用AppOpsManager检查应用程序的权限,反射方法可以不考虑向下兼容问题,同时面对国内各种碎片化的机型以及自定义的属性可以很好的避开crash,因为国内的部门机型对权限的授予结果不同,比如有的机型获取悬浮窗权限的标志为1,有的手机标志为0,通过反射直接获取AppOpsManager类里面定义的获取权限标志MODE_ALLOWED的值来比较结果。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
private boolean CheckePermission(Context context,int op){
try{
//在Context里面定义的AppOpsManager提供的服务,若没有该字段,则没有该服务
final String APP_OPS_SERVICE = "appops";
//加载Context类
Class context_class = Class.forName("android.content.Context");
//加载AppOpsManager类
Class op_class = Class.forName("android.app.AppOpsManager");
//获取AppOpsManager服务字段
Field op_str_field = context_class.getDeclaredField("APP_OPS_SERVICE");
op_str_field.setAccessible(true);
Object op_service_obj = op_str_field.get(context_class);
//若有AppOpsManager服务字段则继续执行
if(op_service_obj !=null && op_service_obj instanceof String){
String op_service_str = (String)op_service_obj;
Method getSysService = context_class.getDeclaredMethod("getSystemService",String.class);
//获取AppOpsManager服务
Object op_service = getSysService.invoke(context,op_service_str);
//获取AppOpsManager定于的权限获取,没获取,错误字段
Field allowed_field = op_class.getDeclaredField("MODE_ALLOWED");
Field ignored_field = op_class.getDeclaredField("MODE_IGNORED");
Field errored_field = op_class.getDeclaredField("MODE_ERRORED");

final int ALLOW = (Integer) allowed_field.get(op_class);
final int IGNORE = (Integer) ignored_field.get(op_class);
final int ERROR = (Integer) errored_field.get(op_class);

Method op_check = op_class.getDeclaredMethod("checkOp",int.class,int.class,String.class);
//检查app是否获取响应的权限
Object result_obj = op_check.invoke(op_service,op, Binder.getCallingUid(),context.getPackageName());
int result_int = (Integer)result_obj;
//若获取指定权限,则返回true
if(result_int == ALLOW){
return true;
}
}
}catch (Exception e){
e.printStackTrace();
}
return false;
}

AppOpsManager提供的部分权限字段

1
2
3
4
5
6
7
8
//大概定位
public static final int OP_COARSE_LOCATION = 0;
//精准定位
public static final int OP_FINE_LOCATION = 1;
//gps权限
public static final int OP_GPS = 2;
//悬浮窗权限
public static final int OP_SYSTEM_ALERT_WINDOW = 24;

具体请前往AppOpsManager的类文件查看:
AppOpsManager

文章目录
  1. 1. AppOpsManager 介绍
  2. 2. 通过反射AppOpsManager检查应用权限
  3. 3. AppOpsManager提供的部分权限字段
,