本文介绍了无法获得正确的存储卷(内部)值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望Phone中有可用的总内部空间,但是在此代码中, getInternalFreeSpace 返回正确的值,但是 getInternalStorageSpace 由于未计算ANDROID OS大小而未返回确切的可用空间.

I want total internal space available in Phone but in this code getInternalFreeSpace returns correct value but getInternalStorageSpace doesn't return exact available space because of not counting ANDROID OS Size.

就像我的手机有64GB,但此代码返回51.6GB.

Like my phone has 64GB but this code returns 51.6GB.

唯一丢失的是12.40 GB,即ANDROID OS大小,51.6GB + 12.40 = 64.00

fun getInternalStorageSpace(): Float{
    val statsFs = StatFs(Environment.getDataDirectory().absolutePath)
    val sizeKB = statsFs.blockCountLong.toFloat() * statsFs.blockSizeLong
    val sizeMB = sizeKB/ (1024 * 1024)
    val sizeGB = sizeMB/1024
    return sizeGB
}

fun getInternalFreeSpace(): Float{
    val statsFs = StatFs(Environment.getDataDirectory().absolutePath)
    val sizeKB = statsFs.availableBlocksLong.toFloat() * statsFs.blockSizeLong
    val sizeMB = sizeKB/ (1024*1024)
    val sizeGB = sizeMB / 1024
    return sizeGB
}

fun getInternalUsedSpace(): Float{
    val statsFs = StatFs(Environment.getDataDirectory().absolutePath)
    val total = statsFs.blockCountLong.toFloat() * statsFs.blockSizeLong / (1024 * 1024)
    val free = statsFs.availableBlocksLong.toFloat() * statsFs.blockSizeLong / (1024 * 1024)
    return total - free
}

推荐答案

尝试这段代码,bytesToMegaBytes方法是简单的转换器.我正在使用StorageManager API.您需要检查每个卷

try this code, the bytesToMegaBytes method is simple converter. I'm using StorageManager API. You need check each volume

 public static int freeStorage(Context context){
    StorageStatsManager storageStatsManager = (StorageStatsManager) context.getSystemService(Context.STORAGE_STATS_SERVICE);
    StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
    try {
        if(storageManager!=null && storageStatsManager!=null) {
            List<StorageVolume> storageVolumes = storageManager.getStorageVolumes();
            for (StorageVolume storageVolume : storageVolumes) {
                final String uuidStr = storageVolume.getUuid();
                final UUID uuid = uuidStr == null ? StorageManager.UUID_DEFAULT : UUID.fromString(uuidStr);
                return  bytesToMegaBytes(storageStatsManager.getFreeBytes(uuid));
            }
        }
        return 0;
    }catch (Exception e){
        Timber.d(e);
        return 0;
    }
}

这篇关于无法获得正确的存储卷(内部)值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-11 21:03