如何从Android应用程序获取SD卡上的可用空间?

我正在开发一个Android应用程序,我需要确定SD卡上的可用空间。 请有人给我一些关于此的建议。

谢谢kaisar

像这样的东西应该工作:

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

您可能需要重新安排才能获得准确的结果:

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

看看这个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; }