Android获取APP缓存大小

        APP设置中需要用到获取APP的缓存大小。

开始我使用glide中的获取缓存大小方式,方式如下:

public String getCacheSize(Context context) {
    try {
        long size1 = getFolderSize(new File(context.getCacheDir() + "/"+ InternalCacheDiskCacheFactory.DEFAULT_DISK_CACHE_DIR));
        long size2 = getFolderSize(new File(path1));
        return getFormatSize(size1 + size2);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}
/**
 * 格式化单位
 *
 * @param size size
 * @return size
 */
private static String getFormatSize(double size) {
    if(size==0){
      return "0MB";
    }
    double kiloByte = size / 1024.0D;
    double megaByte = kiloByte / 1024.0D;
    BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
    return result2.setScale(2, 4).toPlainString() + "MB";
}

该方法有个弊端,无法兼容安卓11,或者部分机型获取到的始终是0,于是我就另写了一种方式。下面是我简单封装的一个获取APP存储大小的类仅供供大家参考(测试有效),如有问题欢迎留言探讨;

public class CacheUtils {
    public static CacheUtils instance = null;

    public static CacheUtils getInstance() {
        if (instance == null) {
            synchronized (CacheUtils.class) {
                instance = new CacheUtils();
            }
        }
        return instance;
    }

    public void init(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            getAppSizeO(context);
        } else {
            getCacheInfo(context);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    public void getAppSizeO(Context context) {
        StorageStatsManager storageStatsManager = (StorageStatsManager) context.getSystemService(Context.STORAGE_STATS_SERVICE);
        StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
        //获取所有应用的StorageVolume列表
        List<StorageVolume> storageVolumes = storageManager.getStorageVolumes();
        for (StorageVolume item : storageVolumes) {
            String uuidStr = item.getUuid();
            UUID uuid = getUuid(uuidStr);
            int uid = getUid(context, context.getPackageName());
            //通过包名获取uid
            StorageStats storageStats;
            try {
                storageStats = storageStatsManager.queryStatsForUid(uuid, uid);
                if (storageStats != null) {
                    EventBus.getDefault().post(size(storageStats.getCacheBytes()));
                } else {
                  
                    storageStats = storageStatsManager.queryStatsForUid(uuid, uid);
                    if (storageStats != null) {
                        EventBus.getDefault().post(size(storageStats.getCacheBytes()));
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private UUID getUuid(String uu) {
        UUID uuid;
        String uuStr = StorageManager.UUID_DEFAULT.toString().replace("-", "");
        if (TextUtils.isEmpty(uu)) {
            uuid = getUU(uuStr);
        } else {
            try {
                uuid = getUU(uu.replace("-", ""));
            } catch (Exception e) {
                Log.i("CacheUtils", "uuid: " + e.getMessage());
                uuid = getUU(uuStr);
                e.fillInStackTrace();
            }
        }
        return uuid;
    }

    private UUID getUU(String uuStr) {
        return new UUID(
                new BigInteger(uuStr.substring(0, 16), 16).longValue(),
                new BigInteger(uuStr.substring(16), 16).longValue());
    }

    public int getUid(Context context, String pakName) {
        try {
            return context.getPackageManager().getApplicationInfo(pakName, PackageManager.GET_META_DATA).uid;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return -1;
    }

    public void getCacheInfo(Context context) {
        try {
            Method method = context.getPackageManager().getClass().getMethod("getPackageSizeInfo"
                    , new Class[]{String.class, IPackageStatsObserver.class});
            // 调用 getPackageSizeInfo 方法,需要两个参数:1、需要检测的应用包名;2、回调
            method.invoke(context.getPackageManager(), context.getPackageName(), new IPackageStatsObserver.Stub() {
                @Override
                public void onGetStatsCompleted(PackageStats pStats, boolean succeeded) {
                    EventBus.getDefault().post(size(pStats.cacheSize));
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 将文件大小显示为GB,MB等形式
     */
    public static String size(long size) {
        if (size / (1024 * 1024 * 1024) > 0) {
            float tmpSize = (float) (size) / (float) (1024 * 1024 * 1024);
            DecimalFormat df = new DecimalFormat("#.##");
            return df.format(tmpSize) + "GB";
        } else if (size / (1024 * 1024) > 0) {
            float tmpSize = (float) (size) / (float) (1024 * 1024);
            DecimalFormat df = new DecimalFormat("#.##");
            return df.format(tmpSize) + "MB";
        } else if (size / 1024 > 0) {
            return (size / (1024)) + "KB";
        } else
            return size + "B";
    }
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值