Naskov
Naskov

Reputation: 4179

Check If There Is Sufficient Memory On SD Card Programmatically

My app is saving files on the SD Card but before I save the files I need to check if there is free memory. I need a to check how much free memory is on the SD Card.

Something like:

if(MemoryCard.getFreeMemory()>20Mb)
{
    saveFiles();
}
else
{
    Toast.makeText(this, "Not enough memory", 100).show();
}

Upvotes: 6

Views: 2288

Answers (3)

stevo.mit
stevo.mit

Reputation: 4731

For Android 4.3+ (API Level: 18+)

StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
long bytesAvailable = getAvailableBytes();

Upvotes: 1

Triode
Triode

Reputation: 11359

StatFs class 

you can use here, provide the path for your internal and external directory and calculate the total, free and avialable space.

StatFs memStatus = new StatFs(Environment.getExternalStorageDirectory().getPath());
long bytesAvailable = (long)memStatus.getBlockSize() * (long)memStatus.getAvailableBlocks();

See the documentation for more details. bytesAvailable is in bytes you can convert it in to which ever format you want.

Upvotes: 7

Shrikant Ballal
Shrikant Ballal

Reputation: 7087

from: http://groups.google.com/group/android-developers/browse_thread/thread/ecede996463a4058

StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
long bytesAvailable = (long)stat.getBlockSize() * (long)stat.getBlockCount();
long megAvailable = bytesAvailable / 1048576;

Upvotes: 4

Related Questions