Android权限管理与AppOpsManager

引言

Android开发中涉及到了许多系统权限,例如网络权限、短信权限等,但是官方并没有把全部的权限都暴露出来,基本的权限检测只能检测到Manifest文件中声明。那一些不需要声明的权限怎么才能获取到呢,例如推送权限,用户如果关闭了推送的我们怎么才能知道呢?这就需要用到我们今天要讲的主角了,Google把他叫App Ops(Application Operations)。

基本权限判断

首先,我们先看下如何检测在Manifest文件中声明的权限

//获取包管理器
PackageManager manager = getPackageManager();

//检测权限。第一个参数是权限名称,第二个参数是包名
int checkPermission = manager.checkPermission(Manifest.permission.INTERNET, getPackageName());
//返回值是一个int类型,官方定义了两种
/**
 * Permission check result: this is returned by {@link #checkPermission}
 * if the permission has been granted to the given package.
 */
public static final int PERMISSION_GRANTED = 0;

/**
 * Permission check result: this is returned by {@link #checkPermission}
 * if the permission has not been granted to the given package.
 */
public static final int PERMISSION_DENIED = -1;

if (checkPermission == PERMISSION_GRANTED){
    //有权限
}else{
    //无权限
}

通过AppOpsManager获取权限

在SDK19中Google引入了AppOpsManager,官方是这样介绍的:

This API is not generally intended for third party application developers; most features are only available to system applications. Obtain an instance of it through Context.getSystemService with Context.APP_OPS_SERVICE.

看Google官方的意思,该类并不建议开发者使用,类中大部分的变量和方法都被hide。而我们需要用的是以下两个方法

public int checkOp(String op, int uid, String packageName) {
    return checkOp(strOpToOp(op), uid, packageName);
}

public int checkOpNoThrow(String op, int uid, String packageName) {
    return checkOpNoThrow(strOpToOp(op), uid, packageName);
}

两个方法的作用是一样的,其中checkOp会抛出SecurityException异常
返回一个int类型的状态值

//有权限
public static final int MODE_ALLOWED = 0;
//无权限
public static final int MODE_IGNORED = 1;

参数分别是:
+ op 权限,目前有64种类型,具体的权限可以在AppOpsManager类中查找到

/** @hide No operation specified. */
public static final int OP_NONE = -1;
/** @hide Access to coarse location information. */
public static final int OP_COARSE_LOCATION = 0;
/** @hide Access to fine location information. */
public static final int OP_FINE_LOCATION = 1;
/** @hide Causing GPS to run. */
public static final int OP_GPS = 2;
/** @hide */
public static final int OP_VIBRATE = 3;
/** @hide */
public static final int OP_READ_CONTACTS = 4;
/** @hide */
public static final int OP_WRITE_CONTACTS = 5;
/** @hide */
public static final int OP_READ_CALL_LOG = 6;
/** @hide */
public static final int OP_WRITE_CALL_LOG = 7;
/** @hide */
public static final int OP_READ_CALENDAR = 8;
/** @hide */
public static final int OP_WRITE_CALENDAR = 9;
/** @hide */
public static final int OP_WIFI_SCAN = 10;
/** @hide */
public static final int OP_POST_NOTIFICATION = 11;
/** @hide */
public static final int OP_NEIGHBORING_CELLS = 12;
/** @hide */
public static final int OP_CALL_PHONE = 13;
/** @hide */
public static final int OP_READ_SMS = 14;
/** @hide */
public static final int OP_WRITE_SMS = 15;
/** @hide */
public static final int OP_RECEIVE_SMS = 16;
/** @hide */
public static final int OP_RECEIVE_EMERGECY_SMS = 17;
/** @hide */
public static final int OP_RECEIVE_MMS = 18;
/** @hide */
public static final int OP_RECEIVE_WAP_PUSH = 19;
/** @hide */
public static final int OP_SEND_SMS = 20;
/** @hide */
public static final int OP_READ_ICC_SMS = 21;
/** @hide */
public static final int OP_WRITE_ICC_SMS = 22;
/** @hide */
public static final int OP_WRITE_SETTINGS = 23;
/** @hide */
public static final int OP_SYSTEM_ALERT_WINDOW = 24;
/** @hide */
public static final int OP_ACCESS_NOTIFICATIONS = 25;
/** @hide */
public static final int OP_CAMERA = 26;
/** @hide */
public static final int OP_RECORD_AUDIO = 27;
/** @hide */
public static final int OP_PLAY_AUDIO = 28;
/** @hide */
public static final int OP_READ_CLIPBOARD = 29;
/** @hide */
public static final int OP_WRITE_CLIPBOARD = 30;
/** @hide */
public static final int OP_TAKE_MEDIA_BUTTONS = 31;
/** @hide */
public static final int OP_TAKE_AUDIO_FOCUS = 32;
/** @hide */
public static final int OP_AUDIO_MASTER_VOLUME = 33;
/** @hide */
public static final int OP_AUDIO_VOICE_VOLUME = 34;
/** @hide */
public static final int OP_AUDIO_RING_VOLUME = 35;
/** @hide */
public static final int OP_AUDIO_MEDIA_VOLUME = 36;
/** @hide */
public static final int OP_AUDIO_ALARM_VOLUME = 37;
/** @hide */
public static final int OP_AUDIO_NOTIFICATION_VOLUME = 38;
/** @hide */
public static final int OP_AUDIO_BLUETOOTH_VOLUME = 39;
/** @hide */
public static final int OP_WAKE_LOCK = 40;
/** @hide Continually monitoring location data. */
public static final int OP_MONITOR_LOCATION = 41;
/** @hide Continually monitoring location data with a relatively high power request. */
public static final int OP_MONITOR_HIGH_POWER_LOCATION = 42;
/** @hide Retrieve current usage stats via {@link UsageStatsManager}. */
public static final int OP_GET_USAGE_STATS = 43;
/** @hide */
public static final int OP_MUTE_MICROPHONE = 44;
/** @hide */
public static final int OP_TOAST_WINDOW = 45;
/** @hide Capture the device's display contents and/or audio */
public static final int OP_PROJECT_MEDIA = 46;
/** @hide Activate a VPN connection without user intervention. */
public static final int OP_ACTIVATE_VPN = 47;
/** @hide Access the WallpaperManagerAPI to write wallpapers. */
public static final int OP_WRITE_WALLPAPER = 48;
/** @hide Received the assist structure from an app. */
public static final int OP_ASSIST_STRUCTURE = 49;
/** @hide Received a screenshot from assist. */
public static final int OP_ASSIST_SCREENSHOT = 50;
/** @hide Read the phone state. */
public static final int OP_READ_PHONE_STATE = 51;
/** @hide Add voicemail messages to the voicemail content provider. */
public static final int OP_ADD_VOICEMAIL = 52;
/** @hide Access APIs for SIP calling over VOIP or WiFi. */
public static final int OP_USE_SIP = 53;
/** @hide Intercept outgoing calls. */
public static final int OP_PROCESS_OUTGOING_CALLS = 54;
/** @hide User the fingerprint API. */
public static final int OP_USE_FINGERPRINT = 55;
/** @hide Access to body sensors such as heart rate, etc. */
public static final int OP_BODY_SENSORS = 56;
/** @hide Read previously received cell broadcast messages. */
public static final int OP_READ_CELL_BROADCASTS = 57;
/** @hide Inject mock location into the system. */
public static final int OP_MOCK_LOCATION = 58;
/** @hide Read external storage. */
public static final int OP_READ_EXTERNAL_STORAGE = 59;
/** @hide Write external storage. */
public static final int OP_WRITE_EXTERNAL_STORAGE = 60;
/** @hide Turned on the screen. */
public static final int OP_TURN_SCREEN_ON = 61;
/** @hide Get device accounts. */
public static final int OP_GET_ACCOUNTS = 62;
/** @hide Control whether an application is allowed to run in the background. */
public static final int OP_RUN_IN_BACKGROUND = 63;
/** @hide */
public static final int _NUM_OP = 64;
  • uid 每个APP对应一个UID,Android中用UID对应用程序进行管理,可以通过getApplicationInfo().uid获取
  • packageName 包名

这里以推送权限为例

if (manager.checkOpNoThrow("OP_POST_NOTIFICATION",getApplicationInfo().uid,getPackageName())
        == AppOpsManager.MODE_ALLOWED){
    //有权限
}else{
    //无权限
}

这样子调用的话会报错,我们看下错误日志
image

没有对应的权限,这是什么原因呢,我们看下源码

//checkOpNoThrow中调用strOpToOp(op)方法,这个方法中从sOpStrToOp这个hashmap中根据键去取对应的值
public int checkOpNoThrow(String op, int uid, String packageName) {
    return checkOpNoThrow(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;
}

//这个hashmap的值是取自于sOpToString这个数组
private static HashMap<String, Integer> sOpStrToOp = new HashMap<>();

for (int i=0; i<_NUM_OP; i++) {
    if (sOpToString[i] != null) {
        sOpStrToOp.put(sOpToString[i], i);
    }
}

//再看看sOpToString这个数组的内容,发现其中好多都是null值,数组中根本没有对应的OP_POST_NOTIFICATION权限,肯定就拿不到对应的int值了, 也就是说我们只能判断manifest中的权限
private static String[] sOpToString = new String[] {
            OPSTR_COARSE_LOCATION,
            OPSTR_FINE_LOCATION,
            null,
            null,
            OPSTR_READ_CONTACTS,
            OPSTR_WRITE_CONTACTS,
            OPSTR_READ_CALL_LOG,
            OPSTR_WRITE_CALL_LOG,
            OPSTR_READ_CALENDAR,
            OPSTR_WRITE_CALENDAR,
            null,
            null,
            null,
            OPSTR_CALL_PHONE,
            OPSTR_READ_SMS,
            null,
            OPSTR_RECEIVE_SMS,
            null,
            OPSTR_RECEIVE_MMS,
            OPSTR_RECEIVE_WAP_PUSH,
            OPSTR_SEND_SMS,
            null,
            null,
            OPSTR_WRITE_SETTINGS,
            OPSTR_SYSTEM_ALERT_WINDOW,
            null,
            OPSTR_CAMERA,
            OPSTR_RECORD_AUDIO,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            OPSTR_MONITOR_LOCATION,
            OPSTR_MONITOR_HIGH_POWER_LOCATION,
            OPSTR_GET_USAGE_STATS,
            null,
            null,
            null,
            OPSTR_ACTIVATE_VPN,
            null,
            null,
            null,
            OPSTR_READ_PHONE_STATE,
            OPSTR_ADD_VOICEMAIL,
            OPSTR_USE_SIP,
            null,
            OPSTR_USE_FINGERPRINT,
            OPSTR_BODY_SENSORS,
            OPSTR_READ_CELL_BROADCASTS,
            OPSTR_MOCK_LOCATION,
            OPSTR_READ_EXTERNAL_STORAGE,
            OPSTR_WRITE_EXTERNAL_STORAGE,
            null,
            OPSTR_GET_ACCOUNTS,
            null,
    };

那如果需要判断推送权限该怎么办呢,就只能使用反射的办法啦

public int checkPermission(Context context,String permissionName){
    if (Build.VERSION.SDK_INT >= 19){
        try {
            AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);

            String pkg = context.getApplicationContext().getPackageName();

            int uid = context.getApplicationInfo().uid;

            Class appOpsClass = Class.forName(AppOpsManager.class.getName());

            Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE, String.class);

            Field opPostNotificationValue = appOpsClass.getDeclaredField(permissionName);

            int value = (int) opPostNotificationValue.get(Integer.class);

            return (int) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg);
        } catch (Throwable e) {
            e.printStackTrace();
            return 1;
        }
    }else{
        return 1;
    }
}

总结

如果只是判断manifest中的权限那就使用checkPermission会更快捷些,但对于一些系统未直接提供的权限,最好事先做好权限判断,无论是对用户体验还是数据统计来说都会有一定的提升。

如有错误的地方欢迎大家留言指正探讨。

猜你喜欢

转载自blog.csdn.net/u012526436/article/details/72819034