public static HashMap<Integer, Long> getPackageSize(Context context, String packageName) { final StorageStatsManager storageStatsManager = (StorageStatsManager) context.getSystemService(Context.STORAGE_STATS_SERVICE); final StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE); final UserHandle user = Process.myUserHandle(); HashMap<Integer, Long> appSizeMap= new HashMap<Integer, Long>(); List<StorageVolume> storageVolumes = storageManager.getStorageVolumes(); for (StorageVolume storageVolume : storageVolumes) { final String uuidStr = storageVolume.getUuid(); // XLog.d("Device: " + storageVolume.getDescription(context.getApplicationContext()) + "'s uuid string=" + uuidStr); final UUID uuid = getUUIDImpl(uuidStr); // XLog.d("Device: " + storageVolume.getDescription(context.getApplicationContext()) + "'s uuid=" + uuidStr); try { final StorageStats storageStats = storageStatsManager.queryStatsForPackage(uuid, packageName, user); long thisAppSize = storageStats.getAppBytes(); long thisDataSize = storageStats.getDataBytes(); long thisCacheSize = storageStats.getCacheBytes(); Log.w("appcommon", "thisCacheSize: " + thisCacheSize); Log.w("appcommon", "thisDataSize: " + thisDataSize); Log.w("appcommon", "thisAppSize: " + thisAppSize); HashMap<Integer, Long> map = new HashMap<Integer, Long>(); map.put(FLAG_APP_CACHE_SIZE,thisCacheSize); map.put(FLAG_APP_DATA_SIZE,thisDataSize); map.put(FLAG_APP_SIZE,thisAppSize); appSizeMap = map; /*Handler mStorageHandler =new Handler(); mStorageHandler.post(() -> { try { StorageStats stats = storageStatsManager.queryStatsForPackage(uuid, packageName, user); long appSize2 = storageStats.getAppBytes(); long dataSize2 = stats.getDataBytes(); long cacheSize2 = stats.getCacheBytes(); Log.w("appcommon", "appSize2: " + appSize2); Log.w("appcommon", "dataSize2: " + dataSize2); Log.w("appcommon", "cacheSize2: " + cacheSize2); } catch (NameNotFoundException | IOException e) { } });*/ } catch (Exception e) { e.printStackTrace(); } } return appSizeMap; }
private static UUID getUUIDImpl(String uuidStr) { if (uuidStr == null) { return StorageManager.UUID_DEFAULT; } else { return UUID.nameUUIDFromBytes(uuidStr.getBytes()); } } //这里输出格式00Mb 00Kb public static String formatSize(Context context, long size) { return Formatter.formatFileSize(context, size); }