Xamarin FileProvider无法在Android中打开文件

时间:2019-03-20 14:59:56

标签: c# xamarin.forms android-fileprovider

在我的Xamarin Forms应用程序中,创建可以用Android应用程序打开的pdf。

在装有Android 7的设备上一切正常,现在我已经在Android 8上对其进行了测试,并且该文件无法打开。

我已经安装了Xam.PluginMedia并保留所有默认设置:

在MainActivity中,我使用以下方法覆盖了OnRequestPermissionsResult函数:

Plugin.Permissions.PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults);

file_paths.xaml是:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-files-path name="my_images" path="Pictures" />
    <external-files-path name="my_movies" path="Movies" />
</paths>

,并在AndroidManifest.xml中添加:

<provider android:name="android.support.v4.content.FileProvider" 
    android:authorities="${applicationId}.fileprovider" 
    android:exported="false" 
    android:grantUriPermissions="true">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"></meta-data>

打开预览的代码是这样的:

public void OpenPreviewFile(string FilePath)
{

    Java.IO.File JavaFile = new Java.IO.File(FilePath);   

    Android.Net.Uri Path = FileProvider.GetUriForFile(global::Android.App.Application.Context, global::Android.App.Application.Context.PackageName + ".fileprovider", JavaFile);

    string Extension = global::Android.Webkit.MimeTypeMap.GetFileExtensionFromUrl(Path.ToString());
    string MimeType = global::Android.Webkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(Extension);
    Intent Intent = new Intent(Intent.ActionView);

    Intent.SetDataAndType(Path, MimeType);
    Intent.AddFlags(ActivityFlags.GrantReadUriPermission);
    Intent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask);

    try
    {
        MainActivity.AppInstance.StartActivity(Intent.CreateChooser(Intent, TS.Translate("ANDROID_ScegliApp")));
    }
    catch (System.Exception)
    {
        Toast.MakeText(MainActivity.AppInstance, TS.Translate("ANDROID_ImpossibileAprireIlFIle"), ToastLength.Short).Show();
    }
}

生成的文件在以下路径下: Android/data/MY_PACKAGE_ID/files/GeneratedReports

我已经附了一段视频,以显示实际行为。

Video

Here一个示例

1 个答案:

答案 0 :(得分:1)

我发现了问题。

file_paths.xml内,节点的“路径”值必须以“ /”开头,

因此,此节点: <files-path name="GeneratedReports" path="/GeneratedReports" />我的代码有效。

我还需要删除MyIntent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask);