Home > Back-end >  Copy opened file into app directory for later use
Copy opened file into app directory for later use

Time:03-02

So I have an android app which opens and displays PDF's, I have the user select pdfs like this

    fun openFile() {
        val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
            addCategory(Intent.CATEGORY_OPENABLE)
            type = "application/pdf"

            putExtra(Intent.EXTRA_MIME_TYPES, arrayOf("application/pdf"))
            putExtra(DocumentsContract.EXTRA_INITIAL_URI, MediaStore.Files.getContentUri("external"))
        }

        activity?.startActivityForResult(intent, REQUEST_CODE_PDF_FILE)
    }

And then I retrieve the URI from the activity result display it and save the URI. However the next time the app is opened I want to be open that same file, right now when I try opening the saved URI I get the following:

ava.lang.SecurityException: Permission Denial: opening provider com.android.providers.media.MediaDocumentsProvider from ProcessRecord{c3dfcb2 32587:ca.thing.testapp/u0a237} (pid=32587, uid=10237) requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs
        at android.os.Parcel.createExceptionOrNull(Parcel.java:2425)
        at android.os.Parcel.createException(Parcel.java:2409)
        at android.os.Parcel.readException(Parcel.java:2392)
        at android.os.Parcel.readException(Parcel.java:2334)
        at android.app.IActivityManager$Stub$Proxy.getContentProvider(IActivityManager.java:5850)
        at android.app.ActivityThread.acquireProvider(ActivityThread.java:6973)

So clearly after closing and reopening the app I no longer have permission to use that selected file. So I imagine what I need to do is make a copy of that file into some cache dir that I do have permissions in so that I can display it when the app is reopened. How would I go about doing that?

CodePudding user response:

You should take persistable uri permission in onActivityResult in order to use the uri later.

Making a copy is not needed.

  • Related