Android get free size of internal/external memory

前端 未结 13 1154
眼角桃花
眼角桃花 2020-11-22 15:20

I want to get the size of free memory on internal/external storage of my device programmatically. I\'m using this piece of code :

StatFs stat = new StatFs(En         


        
13条回答
  •  独厮守ぢ
    2020-11-22 15:28

    Try this simple snippet

        public static String readableFileSize() {
        long availableSpace = -1L;
        StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2)
            availableSpace = (long) stat.getBlockSizeLong() * (long) stat.getAvailableBlocksLong();
        else
            availableSpace = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
    
        if(availableSpace <= 0) return "0";
        final String[] units = new String[] { "B", "kB", "MB", "GB", "TB" };
        int digitGroups = (int) (Math.log10(availableSpace)/Math.log10(1024));
        return new DecimalFormat("#,##0.#").format(availableSpace/Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }
    

提交回复
热议问题