An Android app can create PDF files which should be stored to the external storage and viewed or shared by the user.
Creating, storing and sharing the file is no problem. However viewing the file fails and only a blank screen is shown.
This is my code:
<!-- Provider definition in manifest -->
<provider
android:authorities="com.example.MyApp.fileprovider"
android:name="android.support.v4.content.FileProvider"
android:exported="false"
android:grantUriPermissions="true" >
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
<!-- file_path.xml in xml resource dir -->
<?xml version="1.0" encoding="utf-8"?>
<path xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="ExternalDir" path="Documents/MyApp" />
</path>
// Sharing and viewing
File baseDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
File appDir = new File(baseDir, "MyApp");
appDir.mkdirs();
File pdfFile = new File(appDir, "Test.pdf");
savePDFToFile(pdfFile)
Uri fileUri = FileProvider.getUriForFile(this, "com.example.MyApp.fileprovider", pdfFile);
// View
Intent viewIntent = new Intent(Intent.ACTION_VIEW);
viewIntent .setDataAndType(fileUri, "application/pdf");
viewIntent .addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
viewIntent .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(viewIntent , "View"));
// Sharing
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("application/pdf");
sharingIntent.putExtra(Intent.EXTRA_STREAM, fileUri);
startActivity(Intent.createChooser(sharingIntent, "Share"));
Creating/Writing the PDF file is no problem. Thus there seems to be no problem with the permissions. Sharing the file (e.g. saving it to Google Drive or sending it via email) is also no problem. Thus the FileProvider config and Uri creation seems to be correct.
So, what is wrong with the viewing intent? When testing this in the Emulator using API 26 only a blank page is shown. A user running the same code on a device with API 26 gets a message, that file access is not possible (without a reason).
However the file exists and access permission shouldn't be problem because otherwise the sharing intent would not work as well, would it?
How to solve this?