在 Android 和 IOS 上显示带有 MVVM 交叉的 PDF 文件

Showing PDF-File with MVVM Cross on Android and IOS

我想通过文件路径在 Phone 上打开一个 PDF,但我不知道如何在不使用第 3 方包的情况下正确地做到这一点。

你对此有什么建议吗?

我已经尝试在 Android 上使用它:

public void OpenFile(string filePath)
{
     var fileToOpen = new Java.IO.File(filePath);

     var uri = FileProvider.GetUriForFile(Application.Context, Application.Context.PackageName + ".fileprovider", fileToOpen);
     var intent = new Intent();
     var mime = IOUtil.GetMimeType(uri.ToString());

     intent.SetAction(Intent.ActionView);
     intent.SetDataAndType(uri, mime);
     intent.SetFlags(ActivityFlags.NewTask);
     intent.AddFlags(ActivityFlags.GrantReadUriPermission);

     Application.Context.StartActivity(intent);
}

但我收到以下错误:

Unhandled Exception:

Java.Lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.XmlResourceParser android.content.pm.ProviderInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)' on a null object reference

您的错误告诉我们在传递给函数的匹配位置没有文件。有几种方法可以做到这一点,其中一种如图所示。接受访问文件夹和文件的权限后,这应该是最简单的方法之一。你似乎很接近:

public void OpenPdfFile(string filename)
{
  var f = new Java.IO.File(filename);
  if (f.Exists())
  {
    System.Diagnostics.Debug.WriteLine("File exists!");
    try
    {
      var openFileIntent = new Intent(Intent.ActionView);
      openFileIntent.SetDataAndType(Android.Net.Uri.FromFile(f), "application/pdf");
      openFileIntent.SetFlags(ActivityFlags.NoHistory);

      StartActivity(Intent.CreateChooser(openFileIntent, "Open pdf file"));
    }
    catch (ActivityNotFoundException)
    {
      //handle when no available apps
    }
  }
}

我还没有测试你的工作,但首先要看看你是否将它添加到清单文件中 android:authorities="com.{package}.{name}.fileprovider" 因为你的代码说 Application.Context.PackageName + ".fileprovider"

首先,您应该将此代码添加到您的 manifest 文件中:

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

并创建 filepaths :

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
   <root-path name="root" path="" /> //root directory of the device new File("/");
   <files-path name="files" path="" /> //context.getFilesDir()
   <cache-path name="cache" path="" /> //context.getCacheDir()
   <external-path name="external" path="" /> //Environment.getExternalStorageDirectory()
   <external-files-path name="name" path="path" /> //context.getExternalFilesDirs()
   <external-cache-path name="name" path="path" /> //getExternalCacheDirs()
</paths>