How to check if “android.permission.PACKAGE_USAGE_STATS” permission is given?

后端 未结 4 2045
暗喜
暗喜 2020-11-27 17:02

Background

I\'m trying to get app-launched statistics, and on Lollipop it\'s possible by using the UsageStatsManager class, as such (original post here):

m

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 17:20

    By our investigation: if MODE is default (MODE_DEFAULT), extra permission checking is needed. Thanks to Weien's examination effort.

    boolean granted = false;
    AppOpsManager appOps = (AppOpsManager) context
            .getSystemService(Context.APP_OPS_SERVICE);
    int mode = appOps.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, 
            android.os.Process.myUid(), context.getPackageName());
    
    if (mode == AppOpsManager.MODE_DEFAULT) {
        granted = (context.checkCallingOrSelfPermission(android.Manifest.permission.PACKAGE_USAGE_STATS) == PackageManager.PERMISSION_GRANTED);
    } else {
        granted = (mode == AppOpsManager.MODE_ALLOWED);
    }
    

提交回复
热议问题