AppOpsManager 是在是在Android 4.4版本支持的 (api 19)。获得他实例的方法是
Context.getSystemService(Context.APP_OPS_SERVICE)
AppOpsManager类里有一函数 int checkOp(String op, int uid, String packageName)
public int checkOp(String op, int uid, String packageName) { return checkOp(strOpToOp(op), uid, packageName); } public static int strOpToOp(String op) { Integer val = sOpStrToOp.get(op); if (val == null) { throw new IllegalArgumentException("Unknown operation string: " + op); } return val; }功能就是快速检测某个应用是否具有某些权限,看上面的源码可知道最终调用了下面的代码
public int checkOp(int op, int uid, String packageName) { try { int mode = mService.checkOperation(op, uid, packageName); if (mode == MODE_ERRORED) { throw new SecurityException(buildSecurityExceptionMsg(op, uid, packageName)); } return mode; } catch (RemoteException e) { } return MODE_IGNORED; }op 的值是 0 ~ 47,其中0代表粗略定位权限,1代表精确定位权限,24代表悬浮窗权限。
private static int checkOp(Context context, int op){ final int version = Build.VERSION.SDK_INT; if (version >= 19){ Object object = context.getSystemService("appops"); Class c = object.getClass(); try { Class[] cArg = new Class[3]; cArg[0] = int.class; cArg[1] = int.class; cArg[2] = String.class; Method lMethod = c.getDeclaredMethod("checkOp", cArg); return (Integer) lMethod.invoke(object, op, Binder.getCallingUid(), context.getPackageName()); } catch(NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } return -1; }