How to open Pdf in android 11 from scoped storage

Viewed 2376

I have a question about file permissions in android 11. I am trying to open a PDF file in PDF viewer from my application but I am unable to do that because of the change in permissions in android 11. Can someone please give me a code snippet of how to do that since I am unable to find any code regarding this issue.

I am saving the pdf file in context.getApplicationInfo().dataDir

I have tried to open the pdf file via

        val pdfFile = File(filePath)
        pdfIntent.setDataAndType(Uri.fromFile(pdfFile), "application/pdf")
        pdfIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_NO_HISTORY

        pdfIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        pdfIntent.flags = Intent.FLAG_ACTIVITY_NO_HISTORY
        context.startActivity(pdfIntent)

this code is running on devices below android 11 but not working on android 11.

        val pdfIntent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply { 
                         addCategory(Intent.CATEGORY_OPENABLE) 
                        }
        val pdfFile = File(filePath)
        pdfIntent.setDataAndType(Uri.fromFile(pdfFile), "application/pdf")
        pdfIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_NO_HISTORY

        pdfIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        pdfIntent.flags = Intent.FLAG_ACTIVITY_NO_HISTORY
        context.startActivity(pdfIntent)

I found this code in searching of scope storage but nothing happened

1 Answers

In android 11 do not allow applications to see files of other applications. To share files you need to use a content provider. How to declare and setup are available in the content provider tutorials

Related