简体   繁体   中英

how to obtain available free space on sdcard from android application?

I am developing an android application where i need to determine the free space available on the sdcard. Can anyone give me some suggestion regarding this please.

thanks kaisar

Something like this should work:

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

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());

Check out this function

 private boolean is_sdCardSaveToUse(){

    /**default disk cache size in bytes*/
    final int DEFAULT_DISK_CACHE_SIZE = 1024 * 1024 * 10; //10 MB

    /**get sdCard state*/
    String sdCardState = Environment.getExternalStorageState();

    /**check if the sdCard is mounted*/
    /**check if we can write to sdCard*/if (Environment.MEDIA_MOUNTED.equals(sdCardState)) {
        if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(sdCardState)) {
            Log.d("sdCard", "mounted readOnly");
        } else {
            Log.d("sdCard", "mounted readWrite");

            /**get free usable space in bytes */
            long freeUsableSpace = Environment.getExternalStorageDirectory().getUsableSpace();
            int temp = Math.round(((float) freeUsableSpace / 1024) / 1024); //convert from bytes to MB.
            Log.d("usableSpace= ", Integer.toString(temp) + " MB");

            if (freeUsableSpace > DEFAULT_DISK_CACHE_SIZE){
                return  true;
            } else {
                Log.d("sdCard","not enough space");
                return  false;
            }

        }

    } else{
        Log.d("sdCard","not mounted");
        return false;
    }

   return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM