3 回答

TA貢獻1805條經驗 獲得超10個贊
試試這個代碼:
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
long bytesAvailable = (long)stat.getBlockSize() *(long)stat.getBlockCount();
long megAvailable = bytesAvailable / 1048576;
System.out.println("Megs :"+megAvailable);
更新:
getBlockCount() -SD卡的返回大小;
getAvailableBlocks() -返回普通程序仍可訪問的塊數(感謝喬)

TA貢獻1860條經驗 獲得超8個贊
Yaroslav的答案將給出SD卡的大小,而不是可用空間。StatFs getAvailableBlocks()將返回普通程序仍可訪問的塊數。這是我正在使用的功能:
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 = 0;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2)
bytesAvailable = (long) stat.getBlockSizeLong() * (long) stat.getAvailableBlocksLong();
else
bytesAvailable = (long) stat.getBlockSize() * (long) stat.getAvailableBlocks();
return bytesAvailable / (1024.f * 1024.f);
}

TA貢獻1829條經驗 獲得超7個贊
我設計了一些現成的函數來獲取不同單位的可用空間。您可以通過簡單地將其中任何一種復制到項目中來使用這些方法。
/**
* @return Number of bytes available on External storage
*/
public static long getAvailableSpaceInBytes() {
long availableSpace = -1L;
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
availableSpace = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
return availableSpace;
}
/**
* @return Number of kilo bytes available on External storage
*/
public static long getAvailableSpaceInKB(){
final long SIZE_KB = 1024L;
long availableSpace = -1L;
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
availableSpace = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
return availableSpace/SIZE_KB;
}
/**
* @return Number of Mega bytes available on External storage
*/
public static long getAvailableSpaceInMB(){
final long SIZE_KB = 1024L;
final long SIZE_MB = SIZE_KB * SIZE_KB;
long availableSpace = -1L;
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
availableSpace = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
return availableSpace/SIZE_MB;
}
/**
* @return Number of gega bytes available on External storage
*/
public static long getAvailableSpaceInGB(){
final long SIZE_KB = 1024L;
final long SIZE_GB = SIZE_KB * SIZE_KB * SIZE_KB;
long availableSpace = -1L;
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
availableSpace = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
return availableSpace/SIZE_GB;
}
添加回答
舉報