Lucas Couto
Lucas Couto

Reputation: 31

Can't figure out how to use ACTION_VIEW and Storage Access Framework together

After about a week of pulling my hair out, I'm finally done and ready to ask for some help.

Basically in my app I use the Intent below to create a new PDF, which is done via Storage Access Framework.

val intent = Intent(Intent.ACTION_CREATE_DOCUMENT)
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.type = "application/pdf"
intent.putExtra(Intent.EXTRA_TITLE, title)
startActivityForResult(intent, 1234)

After that I get the Uri on the onActivityResult() method, like so:

uri = dataIntent.data
if (uri != null) {
    val takeFlags = data.flags and (Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
    contentResolver.takePersistableUriPermission(uri, takeFlags)
    generatePdf(uri)
}

PDF generation is ok, the problem comes when I need to call ACTION_VIEW for the user to see the generated file or to share the file using ACTION_SEND.

Example of ACTION_VIEW usage (Yes, I'm using both Kotlin and Java):

Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(uri, mimeType);
startActivity(intent);

I can't for the life of me figure out how to get an Uri that another app can use.

What I tried so far:

If someone could shed some light on this issue would be truly appreciated.

Upvotes: 1

Views: 527

Answers (2)

Lucas Couto
Lucas Couto

Reputation: 31

Like blackapps said in his response, what I had to do was implement a ContentProvider, more specifically a DocumentProvider.

Following this link and this link is what finally did the trick. I implemented a CustomDocumentProvider that exposes a folder inside my app's private files (context.getFilesDir().getAbsolutePath() + "/folderToExpose"), after that all files created in this folder were exposed to other apps and I could use ACTION_VIEW and ACTION_SEND normally.

If someone happens to come across this issue, just make sure that the folder you want to expose doesn't contain any files that are crucial to your app, like database files, since users will have full access to all of its contents. And if it is a new folder, make sure to create it by calling mkdirs().

Upvotes: 1

blackapps
blackapps

Reputation: 9282

In principle use the same uri as obtained at creating the file. But ...you cannot grant a read uri permission on that uri. You got it. But you cannot forward such a permission to a viewer of your document.

Instead you should implement a ContentProvider. Then you can serve the content of your file.

Upvotes: 2

Related Questions