在Android 8.0以后,google出于安全的考虑,废除了以前的方法,但是为我们提供了新的API,我们可以使用StorageStatsManager 类来获取应用大小、用户数据和缓存,从而得到应用的总大小。但是在使用StorageStatsManager 类获取时,我们需要android.permission.PACKAGE_USAGE_STATS 权限。所以在Android 8.0以后要获取应用的总大小,我们必须先申请权限,用户授权了之后才能获取。首先,我们要判断是否开启了android.permission.PACKAGE_USAGE_STATS 权限,代码如下:
(以下代码仅为局部代码!!! 回调代码未贴出!!!)
boolean granted = false;
Context context = activity.getApplicationContext();
AppOpsManager appOps = (AppOpsManager)context
.getSystemService(Context.APP_OPS_SERVICE);
int mode = appOps.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS,
android.os.Process.myUid(), context.getPackageName());
Log.d(TAG, "requestPermission: mode" + mode);
if (mode == AppOpsManager.MODE_DEFAULT) {
granted = (context.checkCallingOrSelfPermission(android.Manifest.permission.PACKAGE_USAGE_STATS) == PackageManager.PERMISSION_GRANTED);
} else {
granted = (mode == AppOpsManager.MODE_ALLOWED);
}
Log.d(TAG, "requestPermission: granted"+granted);
if(granted){
//12 是权限的申请码 Manifest.permission.PACKAGE_USAGE_STATS
//iPermCallBack 为回调接口
iPermCallBack.permissionGranted(12);
}else{
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, requestPermission)) {
//
shouldShowRationale(activity, 12, requestPermission);
} else {
ActivityCompat.requestPermissions(activity, new String[]{requestPermission},12);
}
}
// 以下是展示提示框
private static void shouldShowRationale(Activity activity, int requestCode, String requestPermission) {
showMessageOKCancel(activity, "Rationale:" + requestPermission, (dialog, which) -> {
ActivityCompat.requestPermissions(activity, new String[]{requestPermission}, requestCode);
},null);
}
private static void showMessageOKCancel(Activity activity, String msg, DialogInterface.OnClickListener okListener,DialogInterface.OnClickListener cancelListener) {
new AlertDialog.Builder(activity)
.setMessage(msg)
.setPositiveButton("ok", okListener)
.setNegativeButton("cancel",cancelListener)
.create().show();
}
2.下面是重点
用户获取 Manifest.permission.PACKAGE_USAGE_STATS 权限,不仅需要在androidManifest.xml文件中声明
更需要利用动态权限去申请(ps 非系统软件需要手动授权 )
// 以下方法 为 跳转到手动打开权限的界面
private static void openSettingPackagePermActivity(Activity activity,String msg){
showMessageOKCancel(activity,msg,(dialog,which)->{
Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
activity.startActivity(intent);
},null);
}
作者:苏晨311