I'm struggling with FileProvider. Even following this Google documentation and this post that is pretty much the same as my problem.
So I'm trying to open a pdf file from external storage. The directory is "Download/nst". I provided the path in file_paths.xml
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="br.com.myapp.bomapp"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"/>
</provider>
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="Download" path="Download/" />
</paths>
This is how I get pdf path:
private File getPdfFile(long workOrderId){
File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS+"/nst/"+workOrderId);
String[] filesNames = downloads.list(
new FilenameFilter()
{
public boolean accept(File dir, String name)
{
return name.endsWith(".pdf");
}
}
);
if(filesNames.length > 0){
return new File(downloads, filesNames[0]);
}
return null;
}
And this is how I open pdf:
File pdf = getPdfFile(workOrder.getId());
if(pdf == null){
view.showError(context.getString(R.string.error_no_pdf_found));
return;
}
Intent target = new Intent(Intent.ACTION_VIEW);
Uri fileUri;
if(Build.VERSION.SDK_INT >= 24){
fileUri = FileProvider.getUriForFile(context, "br.com.myapp.bomapp", pdf);
target.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION|Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
else{
fileUri = Uri.fromFile(pdf);
}
target.setDataAndType(fileUri,"application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent = Intent.createChooser(target, "Open File");
try {
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
view.showError(context.getString(R.string.error_no_pdf_reader_found));
}
Notice I'm using Intent.FLAG_GRANT_READ_URI_PERMISSION
.
When debugging the getPdfFile method returns this path for me:
new File(downloads, fileNames[0])": "fileNames[0]=/storage/emulated/0/Download/nst/12345/myName.pdf"
And FileProvider gets me this:
"fileUri = content://br.com.myapp.bomapp/Download/nst/12345/myFile.pdf"
When 12345 is a sub directory which the file is located.
After the file directory is passed to FileProvider it opens the file but screen gets black because file is not there. But when it is opened with Uril.fromFile the file is shown.
Am I doing something wrong?