How to Check available space on android device ? on SD card? [duplicate]

How do I check to see how much MB or GB is left on the android device ? I am using JAVA and android SDK 2.0.1.

Is there any system service that would expose something like this ?


Solution 1:

Yaroslav's answer will give the size of the SD card, not the available space. StatFs's getAvailableBlocks() will return the number of blocks that are still accessible to normal programs. Here is the function I am using:

public static float megabytesAvailable(File f) {
    StatFs stat = new StatFs(f.getPath());
    long bytesAvailable = (long)stat.getBlockSize() * (long)stat.getAvailableBlocks();
    return bytesAvailable / (1024.f * 1024.f);
}

The above code has reference to some deprecated functions as of August 13, 2014. I below reproduce an updated version:

public static float megabytesAvailable(File f) {
    StatFs stat = new StatFs(f.getPath());
    long bytesAvailable = 0;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2)
        bytesAvailable = (long) stat.getBlockSizeLong() * (long) stat.getAvailableBlocksLong();
    else
        bytesAvailable = (long) stat.getBlockSize() * (long) stat.getAvailableBlocks();
    return bytesAvailable / (1024.f * 1024.f);
}

Solution 2:

Try this code:

StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());

long bytesAvailable = (long)stat.getBlockSize() *(long)stat.getBlockCount();
long megAvailable   = bytesAvailable / 1048576;

System.out.println("Megs: " + megAvailable);

Update:

getBlockCount() - return size of SD card;

getAvailableBlocks() - return the number of blocks that are still accessible to normal programs (thanks Joe)