搜索网上的方法,使用storageStatsManager.queryStatsForUid(),获得到的数据不正确,使用queryStatsForPackage才拿到正确的数据
public static long getAppStorage(Context context, String packageName) {
StorageStatsManager storageStatsManager = (StorageStatsManager) context.getSystemService(Context.STORAGE_STATS_SERVICE);
StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
List<StorageVolume> storageVolumes = storageManager.getStorageVolumes();
long appSizeL =0;
for (StorageVolume storageVolume : storageVolumes) {
UUID uuid = null;
String uuidStr = storageVolume.getUuid();
try {
if (TextUtils.isEmpty(uuidStr)){
uuid = StorageManager.UUID_DEFAULT;
}else {
uuid = UUID.fromString(uuidStr);
}
}catch (Exception e){
uuid = StorageManager.UUID_DEFAULT;
}
int uid = 0;
try {
uid = getUid(context, packageName);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
StorageStats storageStats = null;
try {
UserHandle userHandle = Process.myUserHandle();
storageStats = storageStatsManager.queryStatsForPackage(uuid, packageName, userHandle);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
appSizeL = storageStats.getAppBytes() + storageStats.getCacheBytes() + storageStats.getDataBytes();
}
return appSizeL;
}
|