Reputation: 990
I have a FileProvider
in my app, and it pretends like it is working but the files it opens are blank. I have confirmed that the file is already on the device in the specified directory and is not blank, but when I try to open it from inside my app it fails. There is no crash and no error message. Has anyone seen this before?
FileProvider:
<provider android:name="android.support.v4.content.FileProvider" android:authorities="com.my.redacted.provider" android:exported="false" android:grantUriPermissions="true">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/provider_paths" />
</provider>
provider_paths.xml
<?xml version="1.0" encoding="utf-8" ?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_storage" path="." />
</paths>
The code:
var path = "/storage/emulated/0/MyApp/User/attachments/folder/attachment.pdf"
var file = new Java.IO.File(path);
var mime = MimeTypeMap.Singleton;
var ext = MimeTypeMap.GetFileExtensionFromUrl(path).ToLower();
var type = mime.GetMimeTypeFromExtension(ext);
var intent = new Intent();
intent.SetAction(Intent.ActionView);
var name = activity.PackageName + ".provider";
var uri = FileProvider.GetUriForFile(activity.ApplicationContext, name, file);
intent.SetDataAndType(uri, type);
intent.SetFlags(ActivityFlags.GrantReadUriPermission);
intent.SetFlags(ActivityFlags.GrantWriteUriPermission);
var packageManager = activity.PackageManager;
if (intent.ResolveActivity(packageManager) != null)
activity.RunOnUiThread(() => activity.StartActivity(intent));
else
{
var message = "No viewer for attachments: " + type;
activity.RunOnUiThread(() =>
Snackbar.Make(view, message, Snackbar.LengthLong).Show()
);
}
I have debugged to see what the URI ends up being, and it looks right:
uri.Path:
"/external_storage/MyApp/User/attachments/folder/attachment.pdf"
uri.ToString():
"content://com.my.redacted.provider/external_storage/MyApp/User/attachments/folder/attachment.pdf"
So I am really not sure what is going on.
NOTE: I DO have my documents in /storage/emulated/0/MY_STUFF and I did check to make sure that this is what <external-path>
was returning.
Upvotes: 4
Views: 2172
Reputation: 2443
I had the same issue. No pdf reader could open my file provided from FileProvider
.
My solution was adding the flag GRANT_READ_URI_PERMISSION:
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_GRANT_READ_URI_PERMISSION);
Maybe your fault was overriding the FLAG_GRANT_READ_URI_PERMISSION
in your code:
intent.setFlags(ActivityFlags.GrantReadUriPermission);
intent.setFlags(ActivityFlags.GrantWriteUriPermission); <- overrides the 1st flag
Upvotes: 9
Reputation: 11214
The file explorer offers a file system path to it. But now you offer it a content scheme path. Are you shure the viewer can handle a content scheme? Try other apps.
Upvotes: 0