Harvey
Harvey

Reputation: 1375

How to get directory's uuid using StorageManager on Android API below 26?

I created a helper function to check the remaining space of any given directory.

@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
    }
}

Follow this link actually. https://developer.android.com/training/data-storage/app-specific#query-free-space

The problem is I get storageManager!!.getUuidForPath and storageManager.getAllocatableBytes both require for API >= 26.

I did google around but not thing came back on how to get the directory's UUID on API < 26.

Does anyone have any idea how to achieve that?

Thanks

Upvotes: 1

Views: 825

Answers (1)

Harvey
Harvey

Reputation: 1375

Well, I guess I need a different approach. As I googled, UUID required was added when Android O was released. So basically, no such thing gets directory UUID exits before O. This is my helper function now.

@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
    }
}

Upvotes: 3

Related Questions