I am opening pdf file using an external pdf viewer application. But in android 11 shows eacces permission denied issue. All permissions already declared in my manifest file.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Also declared this :
android:requestLegacyExternalStorage="true"
Creating and writing the content with below code :
byte [] decodedContent = Base64.decode(base64.getBytes(), Base64.DEFAULT);
try {
File pdfDirPath = new File(getApplicationContext().getExternalFilesDir(null).getAbsolutePath(), "pdfs");
File file5 = new File(pdfDirPath, globalData.getVin()+".pdf");
if (!file5.exists()) {
file5.getParentFile().mkdirs();
}
outputStream = new FileOutputStream(file5);
outputStream.write(Base64.decode(base64, Base64.NO_WRAP));
outputStream.close();
And open above file like this :
Uri path = FileProvider.getUriForFile(getApplicationContext(), getApplicationContext().getPackageName() + ".helper.ProviderClass", file5);
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Please help me with this.
Two points.
a) A complicated one. Use FileProvider https://developer.android.com/reference/androidx/core/content/FileProvider
b) This one is much simpler one. Since your intention is to share this file with another app, instead of writing into your app's specific directory you should use MediaStore API and write it into the MediaStore.Downloads.EXTERNAL_CONTENT_URI. There are many good examples on the net how to do it, for example How to save pdf in scoped storage? Your PDF Viewer should have no problem accessing it from there.