'Permission denied when trying to open a PDF file (in the default PDF viewer) from an Android app

My app has "Files and media: Allow management of all files" permission. However, when I try to open a PDF file LogCat reports the following errors:

2022-04-20 21:06:30.573 4134-6853/? E/MediaProvider: Permission to access file: /storage/emulated/0/MapDatabase/GuidesPdf/Church guides/Broadwater, Sussex guide book.pdf is denied 2022-04-20 21:06:30.573 24666-26342/? E/DisplayData: openFd: java.io.FileNotFoundException: open failed: EACCES (Permission denied) 2022-04-20 21:06:30.574 24666-26342/? E/PdfLoader: Can't load file (doesn't open) Display Data [PDF : Broadwater, Sussex guide book.pdf] +FileOpenable, uri: file:///storage/emulated/0/MapDatabase/GuidesPdf/Church%20guides/Broadwater%2C%20Sussex%20guide%20book.pdf, has subtitles: false

The code to display the PDF is:

                File pdfFile = new File(Environment.getExternalStorageDirectory().getPath(),"/MapDatabase/GuidesPdf/"+strFolderToShow+"/"+strFileToShow);
                Uri path = Uri.fromFile(pdfFile);
                Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
                pdfIntent.setDataAndType(path, "application/pdf");
                pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(pdfIntent);

I've updated the Min, Compile and TargetSdk versions to match the devices that I want the app to run on now. The build.gradle (Module:app) file now reads as follows:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"

    defaultConfig {
        applicationId "com.prepbgg.mymap"
        minSdkVersion 24
        targetSdkVersion 29
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}

dependencies {
    compile files('libs/jcoord-1.0.jar')
    implementation files('libs/jcoord-1.0.jar')
    implementation "androidx.core:core:1.7.0"
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source