Read text file in Android 11 and above

103 views Asked by At

With the introduction of scope storage that works for media files such as image, audio, and video. How to perform permission checking with without specifying file type in a custom folder? Example directory is /storage/emulated/0/custom_folder containing a non media file.

With media files I can do it with these code.

fun hasImageStoragePermission(context: Context): Boolean {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
        ContextCompat.checkSelfPermission(context, Manifest.permission.READ_MEDIA_IMAGES) ==
                PackageManager.PERMISSION_GRANTED
    else
        hasStoragePermission(context)
}

private fun hasStoragePermission(context: Context): Boolean {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        ContextCompat.checkSelfPermission(context, Manifest.permission.READ_MEDIA_IMAGES) ==
                PackageManager.PERMISSION_GRANTED
    } else {
        true // Android 5.1 and below has no runtime permission thus return true
    }
}

But in our case I am trying to read file like this

fun getFileString() : String? {
    val items: String
    try {
        items = File("/storage/emulated/0/custom_folder/file.txt").bufferedReader().use { it.readText() }
    } catch (e: IOException) {
        e.printStackTrace()
        return null
    }
    return items
}
0

There are 0 answers