Search code examples
javaandroidandroid-contentresolver

Read content Uri from File from SharedPreferences and get persistent permission on it


my app can be called from file explorer via app chooser. I catch the given contentUri from the transmitted PDF file and save the content uri useing sharedPreferences.

If I start my app again, I want to open the saved PDF file (reading the contentUri from from sharedPreferences) again. But no file chooser should be opened anymore.

But I can't call ACTION_OPEN_DOCUMENT via the App Chooser because I get the uri direct from sharedpreferences. I also can't call getContentResolver().takePersistableUriPermission(uri, takeFlags);.

So I can't get access to this file again.

How can I get permanent access to the file. Is copying to INTERNAL_STORAGE really the only solution?

Thanks, Alejandro


Solution

  • I catch the given contentUri from the transmitted PDF file

    Based on your response to my question in the comments, I am interpreting this as: you are getting the Uri from an inbound Intent to one of your activities, such as via ACTION_VIEW or ACTION_SEND.

    and save the content uri useing sharedPreferences

    That is not going to work.

    Think of the Uri as being akin to a URL to a password-protected Web site. So long as the session cookie is good, the URL works, but as soon as that session expires or the cookie is cleared, the URL is useless.

    Similarly, that Uri is good at most for your running process, and there is nothing that you can do about that.

    If you need long-term access to the content, either:

    • Make a copy of that content in some file that you control, or

    • Stop responding to ACTION_VIEW/ACTION_SEND, and instead use ACTION_OPEN_DOCUMENT and takePersistableUriPermission()