如何在内部和外部存储空间中获得可用空间?我正在开发一个下载ROM的应用程序,我必须检查是否有足够的可用空间来下载它。谁能帮我?提前谢谢!
答案 0 :(得分:1)
根据user79758:
这是我正在使用的功能:
public static float megabytesAvailable(File f) {
StatFs stat = new StatFs(f.getPath());
long bytesAvailable = (long)stat.getBlockSize() * (long)stat.getAvailableBlocks();
return bytesAvailable / (1024.f * 1024.f);
}
public static float megabytesAvailable(File f) {
StatFs stat = new StatFs(f.getPath());
long bytesAvailable = (long)stat.getBlockSizeLong() * (long)stat.getAvailableBlocksLong();
return bytesAvailable / (1024.f * 1024.f);
}
答案 1 :(得分:0)
这是一种可以在android中检查内存状态的方法。我在我的申请中实施了。
public class AvailableSpaceHandler {
//*********
//Variables
/**
* Number of bytes in one KB = 2<sup>10</sup>
*/
private final static long SIZE_KB = 1024L;
/**
* Number of bytes in one MB = 2<sup>20</sup>
*/
private final static long SIZE_MB = SIZE_KB * SIZE_KB;
/**
* Number of bytes in one GB = 2<sup>30</sup>
*/
private final static long SIZE_GB = SIZE_KB * SIZE_KB * SIZE_KB;
//********
// Methods
/**
* @return Number of bytes available on external storage
*/
private static long getExternalAvailableSpaceInBytes(int newAndroidAPI) {
long availableSpace = -1L;
try {
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
if (newAndroidAPI >= Build.VERSION_CODES.KITKAT) {
availableSpace = stat.getAvailableBlocksLong() * stat.getBlockSizeLong();
} else {
availableSpace = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
}
} catch (Exception e) {
e.printStackTrace();
}
return availableSpace;
}
/**
* @return Number of kilo bytes available on external storage
*/
public static long getExternalAvailableSpaceInKB(int newAndroidAPI) {
return getExternalAvailableSpaceInBytes(newAndroidAPI) / SIZE_KB;
}
/**
* @return Number of Mega bytes available on external storage
*/
public static long getExternalAvailableSpaceInMB(int newAndroidAPI) {
return getExternalAvailableSpaceInBytes(newAndroidAPI) / SIZE_MB;
}
/**
* @return gega bytes of bytes available on external storage
*/
public static long getExternalAvailableSpaceInGB(int newAndroidAPI) {
return getExternalAvailableSpaceInBytes(newAndroidAPI) / SIZE_GB;
}
/**
* @return Total number of available blocks on external storage
*/
public static long getExternalStorageAvailableBlocks(int newAndroidAPI) {
//newAndroidAPI to check API is < KITKAT
long availableBlocks = -1L;
try {
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
if (newAndroidAPI >= Build.VERSION_CODES.KITKAT) {
availableBlocks = stat.getAvailableBlocksLong();
} else {
availableBlocks = stat.getAvailableBlocks();
}
} catch (Exception e) {
e.printStackTrace();
}
return availableBlocks;
}
}