Memory Size Class for viewing available storage

2 votes · 4 comments

Class used to view available and total storage for internal and external memory. Also does pretty formatting.

raw ·
copy
· download
import java.io.File; import android.os.Environment; import android.os.StatFs; public class MemoryStatus { static final int ERROR = -1; static public boolean externalMemoryAvailable() { return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); } static public long getAvailableInternalMemorySize() { File path = Environment.getDataDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long availableBlocks = stat.getAvailableBlocks(); return availableBlocks * blockSize; } static public long getTotalInternalMemorySize() { File path = Environment.getDataDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long totalBlocks = stat.getBlockCount(); return totalBlocks * blockSize; } static public long getAvailableExternalMemorySize() { if(externalMemoryAvailable()) { File path = Environment.getExternalStorageDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long availableBlocks = stat.getAvailableBlocks(); return availableBlocks * blockSize; } else { return ERROR; } } static public long getTotalExternalMemorySize() { if(externalMemoryAvailable()) { File path = Environment.getExternalStorageDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long totalBlocks = stat.getBlockCount(); return totalBlocks * blockSize; } else { return ERROR; } } static public String formatSize(long size) { String suffix = null; if (size >= 1024) { suffix = "KiB"; size /= 1024; if (size >= 1024) { suffix = "MiB"; size /= 1024; } } StringBuilder resultBuffer = new StringBuilder(Long.toString(size)); int commaOffset = resultBuffer.length() - 3; while (commaOffset > 0) { resultBuffer.insert(commaOffset, ','); commaOffset -= 3; } if (suffix != null) resultBuffer.append(suffix); return resultBuffer.toString(); } }
Add a comment

4 Comments

Reply · June 24, 2009, 1:02 a.m.

Quite nice, although there is some space for minor refinements, e.g. make methods/class and StatFs static... and: Nowadays it is (better: it is suggested to be) KiB and MiB, or even GiB ;-)

Thanx

Reply · June 24, 2009, 2:36 a.m.

I used this class in developing the sound downloader for iFart mobile (android edition). See it in action there.

Reply · July 31, 2009, 3:22 a.m.

Great, works perfectly, Thanks for the share!

Reply · Aug. 1, 2014, 8:54 a.m.