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,
Based on @XXX's answer, I've created a gist code snippet that wraps StatFs for easy and simple usage. You can find it here as a GitHub gist.
Try StatFs.getAvailableBlocks. You'll need to convert the block count to KB with getBlockSize.
Since blocksize and getAvailableBlocks
are deprecated
this code can be use
note based above answer by user802467
public long sd_card_free(){
File path = Environment.getExternalStorageDirectory();
StatFs stat = new StatFs(path.getPath());
long availBlocks = stat.getAvailableBlocksLong();
long blockSize = stat.getBlockSizeLong();
long free_memory = availBlocks * blockSize;
return free_memory;
}
we can use getAvailableBlocksLong
and getBlockSizeLong
/**
* 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";
}