@RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
fun queryStorage() {
val statFs = StatFs(Environment.getExternalStorageDirectory().path)
//存储块总数量
val blockCount = statFs.blockCount.toLong()
//块大小
val blockSize = statFs.blockSize.toLong()
//可用块数量
val availableCount = statFs.availableBlocks.toLong()
//剩余块数量,注:这个包含保留块(including reserved blocks)即应用无法使用的空间
val freeBlocks = statFs.freeBlocks.toLong()
//这两个方法是直接输出总内存和可用空间,也有getFreeBytes
//API level 18(JELLY_BEAN_MR2)引入
val totalSize = statFs.totalBytes
val availableSize = statFs.availableBytes
Log.d("statfs", "total = " + getUnit(totalSize.toFloat()))
Log.d("statfs", "availableSize = " + getUnit(availableSize.toFloat()))
//这里可以看出 available 是小于 free ,free 包括保留块。
Log.d("statfs", "total = " + getUnit(blockSize * blockCount.toFloat()))
Log.d("statfs", "available = " + getUnit(blockSize * availableCount.toFloat()))
Log.d("statfs", "free = " + getUnit(blockSize * freeBlocks.toFloat()))
}
private val units =
arrayOf("B", "KB", "MB", "GB", "TB")
/**
* 单位转换
*/
private fun getUnit(size: Float): String {
var size = size
var index = 0
while (size > 1024 && index < 4) {
size = size / 1024
index++
}
return java.lang.String.format(Locale.getDefault(), " %.2f %s", size, units[index])
}
结果样例:
total = 113.34 GB
availableSize = 63.26 GB
total = 113.34 GB
available = 63.26 GB
free = 63.26 GB
网友评论