Nam*_*tha 15 android android-sdcard android-external-storage
如何检查SD卡是否已满,以便您的应用程序可以决定是否可以继续执行其工作,即写入外部存储器或通知用户存储空间不足.
Jon*_*nik 14
此答案中 的方法在具有大型外部存储的设备上被破坏.例如,在我的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;
Run Code Online (Sandbox Code Playgroud)
的statfs确实有替代方法返回long
,getAvailableBlocksLong()
和getBlockCountLong()
,但问题是,他们是在只增加API等级18.
最简单的方法是getFreeSpace()
在java.io.File中使用,在API级别9中添加,它返回long
:
返回包含此路径的分区上的空闲字节数.如果此路径不存在,则返回0.
因此,要获得外部存储空间("SD卡")的可用空间:
File externalStorageDir = Environment.getExternalStorageDirectory();
long free = externalStorageDir.getFreeSpace() / 1024 / 1024;
Run Code Online (Sandbox Code Playgroud)
或者,如果您确实想使用StatF但需要支持API级别<18,这将修复整数溢出:
File externalStorageDir = Environment.getExternalStorageDirectory();
StatFs statFs = new StatFs(externalStorageDir.getAbsolutePath());
long blocks = statFs.getAvailableBlocks();
long free = (blocks * statFs.getBlockSize()) / 1024 / 1024;
Run Code Online (Sandbox Code Playgroud)
XXX*_*XXX 12
/******************************************************************************************
Returns size in MegaBytes.
If you need calculate external memory, change this:
StatFs statFs = new StatFs(Environment.getRootDirectory().getAbsolutePath());
to this:
StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
******************************************************************************************/
public long totalMemory()
{
StatFs statFs = new StatFs(Environment.getRootDirectory().getAbsolutePath());
long total = (statFs.getBlockCount() * statFs.getBlockSize()) / 1048576;
return total;
}
public long freeMemory()
{
StatFs statFs = new StatFs(Environment.getRootDirectory().getAbsolutePath());
long free = (statFs.getAvailableBlocks() * statFs.getBlockSize()) / 1048576;
return free;
}
public long busyMemory()
{
StatFs statFs = new StatFs(Environment.getRootDirectory().getAbsolutePath());
long total = (statFs.getBlockCount() * statFs.getBlockSize()) / 1048576;
long free = (statFs.getAvailableBlocks() * statFs.getBlockSize()) / 1048576;
long busy = total - free;
return busy;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8877 次 |
最近记录: |