Android 記憶體卡 / Micro SD 卡 / TF 卡 / 儲存卡 剩餘容量 / 剩餘記憶體 / 可用空間、總容量的 2 種獲取方式
阿新 • • 發佈:2019-02-01
1 採用 Java 的 File 類
// 總容量
public long getStorageTotalSpace(String path) {
File file = new File(path);
return file.getTotalSpace();
}
// 可用容量
public long getStorageAvailableSpace(String path) {
File file = new File(path);
// getUsableSpace 比 getFreeSpace 準確
return file.getUsableSpace();
}
2 採用 Android 的 StatFs 類
// 總容量
public long getStorageTotalSpace(String path) {
StatFs statFs = new StatFs(path);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
return statFs.getTotalBytes();
} else {
return statFs.getBlockSizeLong() * statFs.getBlockCountLong();
}
}
// 可用容量
public long getStorageAvailableSpace(String path) {
StatFs statFs = new StatFs(path);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
// getAvailableBytes 比 getFreeBytes 準確
return statFs.getAvailableBytes();
} else {
// getAvailableBlocksLong 比 getFreeBlocksLong 準確
return statFs.getBlockSizeLong() * statFs.getAvailableBlocksLong();
}
模擬器測試:
真機測試:
ES 檔案瀏覽器 顯示的是【已用容量 / 總容量】,另外小數可能會有誤差