S
S
Sergey Shilovsky2022-01-22 16:26:49
Android
Sergey Shilovsky, 2022-01-22 16:26:49

How to access a file by URI in Android 11?

The user selects any ringtone from the device, this ringtone is played when some event occurs.
Before android 11, the following code worked perfectly:

fun onSomeEvent() {
    val uri = preferences.ringtoneUri
    val ringtone = RingtoneManager.getRingtone(appContext, uri)
    ringtone.play()
}

fun onChangeRingtoneClick() {
    val intent = Intent(RingtoneManager.ACTION_RINGTONE_PICKER)
    intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION)
    startActivityForResult(intent, REQUEST_CODE)
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
        preferences.ringtoneUri = data?.extras?.get(EXTRA_RINGTONE_PICKED_URI)
    }
}


In Android 11, access by URI is available only after the user selects a ringtone ( Calling onChangeRingtoneClick ). If the application is restarted, then access by URI will be lost and the user must select it again.

The URI is always the same (the user selects the same ringtone), but before receiving it, via onActivityResult , there is no access to the ringtone, but after that.

That is, as I understand it, now the android remembers which uri were received in onActivityResult and if they were received within the life of the process, then there is access to files through them, and if they were not, then there is no access.

How to be now? I can't ask the user to select the ringtone again after each launch of the application.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question