SHINCHVEN'S HEXO

Take All Persistable Uri Permissions At A Time If You Want Them To Last Over ...

Count: 179Reading time: 1 min
2019/11/25 Share

If I don’t get it wrong, declaring for the android.permission.WRITE_EXTERNAL_STORAGE permission is bundled with android.permission.READ_EXTERNAL_STORAGE, so in old ways if I am a lazy guy, I just don’t have to write the permission declaration for the later one.

But time has changed when Google’s new policy is asking developers to use Storage Access Framework, when taking the persistable uri permissions, you must take reading and writing permission both at one. Other wise you won’t be able to read or write after reboot. To do so you can use the following kotlin codes:

1
class StoragePermissionFragment : Fragment(){
2
3
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
4
        super.onActivityResult(requestCode, resultCode, data)
5
        if (requestCode == OPEN_DIRECTORY_REQUEST_CODE) {
6
            if (resultCode == Activity.RESULT_OK) {
7
                val directoryUri = data?.data ?: return
8
                activity?.contentResolver?.takePersistableUriPermission(
9
                    directoryUri,
10
                    // take both permissions at a time by combining flags with `or` operator
11
                    Intent.FLAG_GRANT_WRITE_URI_PERMISSION
12
                    or Intent.FLAG_GRANT_READ_URI_PERMISSION
13
                )
14
            } else if (resultCode == Activity.RESULT_CANCELED) {
15
                // handle canceled
16
            }
17
        }
18
    }
19
}
CATALOG