我创建了一个帮助函数来检查任何给定目录的剩余空间。
@RequiresApi(Build.VERSION_CODES.O)
fun Context.hasFreeSpace(directory: File, requiredStorageSpace: Long): Boolean{
return try {
val storageManager = getSystemService<StorageManager>()
val directoryUUID = storageManager!!.getUuidForPath(directory)
val availableBytes = storageManager.getAllocatableBytes(directoryUUID)
availableBytes > requiredStorageSpace
}catch (e: Exception){
e.printStackTrace()
false
}
}请实际使用此链接。https://developer.android.com/training/data-storage/app-specific#query-free-space
问题是我得到的storageManager!!.getUuidForPath和storageManager.getAllocatableBytes都需要>= 26接口。
我在谷歌上搜索了一下,但在API < 26上如何获取目录的UUID的问题上没有结果。
有谁知道如何做到这一点吗?
谢谢
发布于 2021-03-30 02:21:30
好吧,我想我需要一个不同的方法。我在谷歌上搜索时,Android O发布时添加了UUID required。所以基本上,在O之前没有这样的东西获取目录UUID。这是我现在的助手函数。
@SuppressLint("NewApi")
fun Context.hasFreeSpace(directory: File, requiredStorageSpace: Long): Boolean {
return try {
val api = Build.VERSION.SDK_INT
val availableBytes = when {
api >= Build.VERSION_CODES.O -> {
val storageManager = getSystemService<StorageManager>()
val directoryUUID = storageManager!!.getUuidForPath(directory)
storageManager.getAllocatableBytes(directoryUUID)
}
else -> {
val stat = StatFs(directory.path)
stat.availableBlocksLong * stat.blockSizeLong
}
}
availableBytes > requiredStorageSpace
} catch (e: Exception) {
e.printStackTrace()
false
}
}https://stackoverflow.com/questions/66859325
复制相似问题