Search code examples
androidkotlinpdfandroid-intentpermissions

Opening pdf file from documents of internal storage in Android has issue


I am creating an Android app that I save some files in Documents of internal storage and then I want to open that pdf file in app programmatically. I have searched a lot and now I can open Documents but I can't open the pdf file directly. What should I change in the code? please help me. In Manifest I added this:

 <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.provider1"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths" />
        </provider>

As provider_paths.xml I have this:

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path name="external_files" path="."/>
</paths>

And as code in activity I have this:

 val fileName = "order5.pdf"
        val file = File(File(Environment.getExternalStorageDirectory(),"Documents"), fileName)
        val fileUri = FileProvider.getUriForFile(this, "com.example.repo.provider1", file)
        val intent = Intent(Intent.ACTION_VIEW).apply {
            setDataAndType(fileUri, "application/pdf")
            flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
        }
        startActivity(intent)

File is identified correctly. I think I should make change in intent.


Solution

  • Finally I found my problem. I have two providers in manifest and it made conflict. See this great question and answer for more details: https://stackoverflow.com/a/53512552/12478830