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,
/**
* Returns the amount of free memory.
* @return {@code long} - Free space.
*/
public long getFreeInternalMemory() {
return getFreeMemory(Environment.getDataDirectory());
}
/**
* Returns the free amount in SDCARD.
* @return {@code long} - Free space.
*/
public long getFreeExternalMemory() {
return getFreeMemory(Environment.getExternalStorageDirectory());
}
/**
* Returns the free amount in OS.
* @return {@code long} - Free space.
*/
public long getFreeSystemMemory() {
return getFreeMemory(Environment.getRootDirectory());
}
/**
* Returns the free amount in mounted path
* @param path {@link File} - Mounted path.
* @return {@code long} - Free space.
*/
public long getFreeMemory(File path) {
if ((null != path) && (path.exists()) && (path.isDirectory())) {
StatFs stats = new StatFs(path.getAbsolutePath());
return stats.getAvailableBlocksLong() * stats.getBlockSizeLong();
}
return -1;
}
/**
* Convert bytes to human format.
* @param totalBytes {@code long} - Total of bytes.
* @return {@link String} - Converted size.
*/
public String bytesToHuman(long totalBytes) {
String[] simbols = new String[] {"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"};
long scale = 1L;
for (String simbol : simbols) {
if (totalBytes < (scale * 1024L)) {
return String.format("%s %s", new DecimalFormat("#.##").format((double)totalBytes / scale), simbol);
}
scale *= 1024L;
}
return "-1 B";
}