1. 程式人生 > >Android許可權管理與AppOpsManager

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會更快捷些,但對於一些系統未直接提供的許可權,最好事先做好許可權判斷,無論是對使用者體驗還是資料統計來說都會有一定的提升。

如有錯誤的地方歡迎大家留言指正探討。