How to get available space on Android SD card?

I use Environment.getExternalStorageDirectory () to create the file, and I will need to know if there is enough free space before creating and storing the file.

If you can provide a link to Android Ref, this will be useful too.

+3
source share
4 answers

You must use the StatFs class . Below is an example of using it from the source code in 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;
        }
+6
source

StatFS. , Environment.getExternalStorageDirectory() (, String).

+2

You may need to reinstall to get accurate results:

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

Used from API level 9:

Environment.getExternalStorageDirectory().getUsableSpace();

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

0
source

Source: https://habr.com/ru/post/1764197/


All Articles