androidkotlinpdfpermissions

Saving PDF from Third Party App Causes Permission Issue - Android Kotlin


I have an app which copies .pdf files from assets and saves them locally. The user can then open the .pdf in a third party app using intents to make annotations and then save the .pdf. Once the user saves the annotated .pdf, I now lose permission to the .pdf. For instance, if they save it in the same location (overwriting original file), I receive EACCES PERMISSION DENIED when trying to reopen it. If the user saves it in a separate directory, I don't receive an error but it's as if the file doesn't exist. When I check to see if the directory exists with .exists(), it returns true but when I run listFiles() on the directory, it returns null.

Below is an example of the directory I am using.

Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS + "/Folder Name")
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS + "/Folder Name").exists()
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS + "/Folder Name").listFiles()

My understanding is I don't need to request permissions but for the heck of it, I did add <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> to my manifest and this did not solve the issue. Any ideas why this is happening?


Solution

  • You only have access to files in Documents/ that were created by your app. A typical approach to saving changes to a file, particularly one like a PDF, is to write out a new file under a temporary name, delete the original file, then rename the new file to the original file's name. A side effect of this technique is that your app loses rights to access the file, because you created the now-deleted original copy, not the modified one.

    Please use the Storage Access Framework:

    This not only lets you get past the permission issues, but it gives the user freedom to store the PDFs where they want, rather than your hard-coded location.