您如何检查 SD 卡是否已满,以便您的应用程序可以决定它是否可以继续执行其工作,即写入外部存储或通知用户存储空间已用完。
最佳答案
注意新设备上的 StatFs 和 int 溢出
this answer 中的方法在具有大型外部存储空间的设备上损坏。 例如,在我的 Nexus 7 上,它当前返回约 2 GB,而实际上还剩下约 10 GB 的空间。
// DOES NOT WORK CORRECTLY ON DEVICES WITH LARGE STORAGE DUE TO INT OVERFLOW
File externalStorageDir = Environment.getExternalStorageDirectory();
StatFs statFs = new StatFs(externalStorageDirectory.getAbsolutePath());
int free = (statFs.getAvailableBlocks() * statFs.getBlockSize()) / 1024 / 1024;
StatFs 确实有返回 long
、getAvailableBlocksLong()
的替换方法和 getBlockCountLong()
,但问题是它们仅在 API 级别 18 中添加。
改用这个
最简单的方法是使用getFreeSpace()
in java.io.File ,在 API 级别 9 中添加,返回 long
:
Returns the number of free bytes on the partition containing this path. Returns 0 if this path does not exist.
因此,要在外部存储(“SD 卡”)上获得可用空间:
File externalStorageDir = Environment.getExternalStorageDirectory();
long free = externalStorageDir.getFreeSpace() / 1024 / 1024;
或者,如果您真的想要使用 StatFs 但需要支持 API 级别 < 18,这将修复整数溢出:
File externalStorageDir = Environment.getExternalStorageDirectory();
StatFs statFs = new StatFs(externalStorageDir.getAbsolutePath());
long blocks = statFs.getAvailableBlocks();
long free = (blocks * statFs.getBlockSize()) / 1024 / 1024;
关于android - 如何检查外部存储空间的可用性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3163045/