I am creating a PDF file and saving it in local storage. When trying to open it, it is working perfect in all devices except in Android N. I am able to open PDF file in Android N using FileProvider, but it is displaying as blank.
This is my URI
content://com.products.provider/external_storage_root/Android/data/com.products/in_17052017_170502_1_1001.pdf
This is my code
Uri path;
File pdfFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/"
+ "Android" + "/" + "data" + "/" + "com.products" + "/" + file);
if (Build.VERSION.SDK_INT >= 24) {
path = FileProvider.getUriForFile(getActivity(), "com.products.provider", pdfFile);
} else {
path = Uri.fromFile(pdfFile);
}
// Setting the intent for pdf reader
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
try {
startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(getActivity(), "Can't read pdf file", Toast.LENGTH_SHORT).show();
}
The problem is with how you are setting the flags on the intent
Instead, try this:
As I can see that you have used
FileProvider
for Nougat. You have to add a FileProvider tag in AndroidManifest.xml.A FileProvider can only generate a content URI for files in directories that you specify beforehand.To link this file to the FileProvider, add a element as a child of the element that defines the FileProvider.
You must specify a child element of for each directory that contains files for which you want content URIs. You can add them to a new file called
res/xml/file_paths.xml
. For example ,these XML elements specify two directories:->you have to set your PDF directory path in
file_paths.xml
For more detail refer this
Grzegorz Matyszczak's solution worked for my case. I had a very similar setup to Sabya Sachi. More specifically this line allowed me to see the PDF file (URI from FileProvider.getURIForFile call):
More info on
grantUriPermissions
here, underandroid:grantUriPermissions
section.