驱动器无法打开PDF文件

4

用例: 在Android中通过设备上的任何PDF阅读器应用程序(例如:GDrive)打开存储在我的应用程序名称目录中的PDF文档。

     intent = new Intent(Intent.ACTION_VIEW);
                            intent.setDataAndType(Uri.fromFile(file), "application/pdf");
                            intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
       context.startActivity(intent);

问题:根据我的分析,它在Android 9及以下设备上运行良好,但在Android 10上会出现问题。

发生了什么:PDF名称显示在Gdrive PDF查看器标题中,但PDF不会呈现并将用户带回到我的应用程序。

存在问题的设备:三星S10(不知道Android版本)、OnePlus A6000(Android 10)、三星A70(不知道Android版本)、诺基亚6.1 Plus(Android 10)、OnePlus 6T(不知道Android版本)。

虽然也有运行Android 10但没有问题的设备。

没有问题的设备:三星GalaxyS20(Android 10)。

也有一些设备以前没有问题,现在开始出问题,反之亦然(即问题自动解决)。

这个问题非常令人困惑,我无法找到根本原因。

我尝试过: 1. 检查日志:没有错误/异常记录

  1. 检查意图的结果代码,也没有问题。
  2. 权限:应用内:媒体、相机和存储 权限:在Drive中:存储权限:已启用

我还阅读了Android 10的文档。

要允许其他应用程序访问存储在内部存储器中的此目录中的文件,请使用带有FLAG_GRANT_READ_URI_PERMISSION属性的FileProvider。

     intent = new Intent(Intent.ACTION_VIEW);
                            intent.setDataAndType(Uri.fromFile(file), "application/pdf");
                            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION|Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
  1. 没有pdf问题,因为使用另一个pdf阅读器(例如: Adobe)打开相同的pdf文件时,它可以完美地工作。

当前应用程序

   compileSdkVersion 28
    minSdkVersion 19
    targetSdkVersion 28

我只是想简单解决这个问题。我有一些疑问:

  1. 这是Android 10的问题,还是仅仅是我的代码问题?

  2. 将应用程序与Android 10兼容能否解决此问题?

  3. 如何调试它?

如果我漏掉了任何情况,请告诉我。提前致谢。


3
请使用FileProvider。 - blackapps
2
你的意图不应该在Q/10以下运行。它应该会产生FileUriExposedException异常。 - blackapps
问题出在没有使用文件提供程序。谢谢。 - PRIYANSHI
1个回答

1
尽管使用FileProvider已经可以解决驱动pdf阅读器问题,但我仍然想分享使用FileProvider的实现方式。具体操作如下:
1- 添加xml文件夹并创建path.xml add xml folder 2- 在path.xml中添加以下代码以配置目录内的文件访问 我将pdf文件位置设置在下载目录中。
<paths>
    <external-path
        name="external"
        path="."/>
</paths>

3 - 在AndroidManifest.xml中添加元数据

<application
   ...>
        {...}
        <provider
            android:authorities="com.example.myapplication"
            android:name="androidx.core.content.FileProvider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths" />
        </provider>
</application>

4 - 使用意图操作读取PDF文件

var uri = FileProvider.getUriForFile(
      this, "com.example.applicationid", File(
        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
          .toString() +
                "/" + "yourfile.pdf"
      )
    )
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/pdf")
var builder = StrictMode.VmPolicy.Builder()
StrictMode.setVmPolicy(builder.build())
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
startActivity(intent)

运行应用程序并尝试使用驱动PDF查看器打开它,然后哇!希望能帮助大家!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接