mobibob
mobibob

Reputation: 8794

How to get the available space on Android sdcard?

I am using Environment.getExternalStorageDirectory() to create a file and I will need to know if there is enough space available before I create and store the file.

If you can cite the Android Ref doc, that would be helpful too.

Upvotes: 3

Views: 5041

Answers (4)

tknell
tknell

Reputation: 9047

Usable since API level 9:

Environment.getExternalStorageDirectory().getUsableSpace();

http://developer.android.com/reference/java/io/File.html#getUsableSpace()

Upvotes: 0

Merkidemis
Merkidemis

Reputation: 2851

You may have to restat to get accurate results:

StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
stat.restat(Environment.getExternalStorageDirectory().getAbsolutePath());
long available = ((long) stat.getAvailableBlocks() * (long) stat.getBlockSize());

Upvotes: 1

Nathan Schwermann
Nathan Schwermann

Reputation: 31493

You have to use the StatFs Class. Here is an example of how to use it taken from the source code to the Settings application found on the phone.

        if (status.equals(Environment.MEDIA_MOUNTED)) {
        try {
            File path = Environment.getExternalStorageDirectory();
            StatFs stat = new StatFs(path.getPath());
            long blockSize = stat.getBlockSize();
            long totalBlocks = stat.getBlockCount();
            long availableBlocks = stat.getAvailableBlocks();

            mSdSize.setSummary(formatSize(totalBlocks * blockSize));
            mSdAvail.setSummary(formatSize(availableBlocks * blockSize) + readOnly);

            mSdMountToggle.setEnabled(true);
            mSdMountToggle.setTitle(mRes.getString(R.string.sd_eject));
            mSdMountToggle.setSummary(mRes.getString(R.string.sd_eject_summary));

        } catch (IllegalArgumentException e) {
            // this can occur if the SD card is removed, but we haven't received the 
            // ACTION_MEDIA_REMOVED Intent yet.
            status = Environment.MEDIA_REMOVED;
        }

Upvotes: 6

CommonsWare
CommonsWare

Reputation: 1006614

Use StatFS. It should work if you pass in the value from Environment.getExternalStorageDirectory() to the constructor (converting to String, of course).

Upvotes: 2

Related Questions