How to find the amount of free storage (disk space) left on Android?

后端 未结 10 1223
遇见更好的自我
遇见更好的自我 2020-12-02 14:25

I am trying to figure out the available disk space on the Android phone running my application. Is there a way to do this programmatically?

Thanks,

10条回答
  •  时光说笑
    2020-12-02 15:06

    Memory Locations:

    File[] roots = context.getExternalFilesDirs(null);
    String path = roots[0].getAbsolutePath(); // PhoneMemory
    String path = roots[1].getAbsolutePath(); // SCCard (if available)
    String path = roots[2].getAbsolutePath(); // USB (if available)
    

    usage

    long totalMemory = StatUtils.totalMemory(path);
    long freeMemory = StatUtils.freeMemory(path);
    
    final String totalSpace = StatUtils.humanize(totalMemory, true);
    final String usableSpace = StatUtils.humanize(freeMemory, true);
    

    You can use this

    public final class StatUtils {
    
        public static long totalMemory(String path) {
            StatFs statFs = new StatFs(path);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
                //noinspection deprecation
                return (statFs.getBlockCount() * statFs.getBlockSize());
            } else {
                return (statFs.getBlockCountLong() * statFs.getBlockSizeLong());
            }
        }
    
        public static long freeMemory(String path) {
            StatFs statFs = new StatFs(path);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
                //noinspection deprecation
                return (statFs.getAvailableBlocks() * statFs.getBlockSize());
            } else {
                return (statFs.getAvailableBlocksLong() * statFs.getBlockSizeLong());
            }
        }
    
        public static long usedMemory(String path) {
            long total = totalMemory(path);
            long free = freeMemory(path);
            return total - free;
        }
    
        public static String humanize(long bytes, boolean si) {
            int unit = si ? 1000 : 1024;
            if (bytes < unit) return bytes + " B";
            int exp = (int) (Math.log(bytes) / Math.log(unit));
            String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i");
            return String.format(Locale.ENGLISH, "%.1f %sB", bytes / Math.pow(unit, exp), pre);
        }
    }
    

提交回复
热议问题