Basically, I'm trying to let users choose pictures from their phone's image gallery to use as background images in my app.
Here is my code:
private val pickImages = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
// e.g. content://com.android.providers.media.documents/document/image%3A31
android.util.Log.d("dev-", "uri = $uri?.toString()")
uri?.let {
// save uri to my DB, etc.
}
}
My concern is: what happens if the user deletes the images or switches to a new phone. The URI should break, right? And a better approach would be to save the picture to my local app storage and save a URI that points there?
However, I've tried deleting the picture from my phone's gallery, resetting the gallery cache, close & re-open the app, restarting the phone...and I'm still able to the image in my app.
Is it really necessary to create my own copy of the file?
How long does the URI I'm given by registerForActivityResult(ActivityResultContracts.GetContent()) last?
I found this SO post & this article by CommonsWare, but nothing else online and I haven't encountered any errors yet...
Note: I've been testing on Android 12 API 31.
Update:
I finally found official documentation that answers my question.
When your app opens a file for reading or writing, the system gives your app a URI permission grant for that file, which lasts until the user's device restarts.