Android 获取应用占用存储空间大小

搜索网上的方法,使用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;
            }
            //通过包名获取uid
            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;
            }
            //获取到App的总大小
            appSizeL = storageStats.getAppBytes() + storageStats.getCacheBytes() + storageStats.getDataBytes();
        }
        return appSizeL;
    }

你可能感兴趣的:(Android,android,android,studio,android-studio)