简体   繁体   中英

Open pdf viewer from content uri at Android Q

I store the pdf file using this code:

val intent = Intent().apply {
            action = Intent.ACTION_CREATE_DOCUMENT
            addCategory(Intent.CATEGORY_OPENABLE)
            type = "application/pdf"
            putExtra(Intent.EXTRA_TITLE, file.name)
        }
startActivityForResult(intent, SAVE_FILE_REQUEST_CODE)

and after at onActivityResult Im saving data using OutputStream. Uri to file can look like:

content://com.android.providers.downloads.documents/document/4594
or
content://com.google.android.apps.docs.storage/document/documentId

But when im trying to start activity with this intent, pdf viewer app show error:

 val openFileIntent = Intent(Intent.ACTION_VIEW, contentUri)
                            .apply {
                                setDataAndType(contentUri, "application/pdf")
                                addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
                            }

Is it possible to open pdf viewer activity from content Uri?

I can confirm that the Comments have the answer: blackapps and Андрей Макаренко

val target = Intent(Intent.ACTION_VIEW)
target.setDataAndType(uri, "application/pdf")
target.flags = Intent.FLAG_ACTIVITY_NO_HISTORY or Intent.FLAG_GRANT_READ_URI_PERMISSION

val intent: Intent = Intent.createChooser(target, "Open File")

try {
     startActivity(intent)
} catch (e: ActivityNotFoundException) {
     // Instruct the user to install a PDF reader here
}

Adding the "or Intent.FLAG_GRANT_READ_URI_PERMISSION" to the flags got my PDF reader to open the file correctly with the content:// Uri structure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM