Not getting correct value of Storage Volume(Internal)

不羁的心 提交于 2021-02-11 13:41:30

问题


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.

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

The Only missing is 12.40 GB i.e. ANDROID OS size, 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
}


回答1:


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;
    }
}


来源:https://stackoverflow.com/questions/62797927/not-getting-correct-value-of-storage-volumeinternal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!