首页 > 解决方案 > 如何使用 FileProvider 查看/显示 PDF 文件?仅显示空白屏幕

问题描述

Android 应用程序可以创建 PDF 文件,这些文件应该存储到外部存储并供用户查看或共享。

创建、存储和共享文件没有问题。但是查看文件失败,只显示一个空白屏幕。

这是我的代码:

<!-- Provider definition in manifest -->
<provider
    android:authorities="com.example.MyApp.fileprovider"
    android:name="android.support.v4.content.FileProvider"
    android:exported="false"
    android:grantUriPermissions="true" >
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>


<!-- file_path.xml in xml resource dir -->
<?xml version="1.0" encoding="utf-8"?>
<path xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="ExternalDir" path="Documents/MyApp" />
</path>


// Sharing and viewing
File baseDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
File appDir = new File(baseDir, "MyApp");
appDir.mkdirs();

File pdfFile = new File(appDir, "Test.pdf");
savePDFToFile(pdfFile)


Uri fileUri = FileProvider.getUriForFile(this, "com.example.MyApp.fileprovider", pdfFile);

// View
Intent viewIntent = new Intent(Intent.ACTION_VIEW);
viewIntent .setDataAndType(fileUri, "application/pdf");
viewIntent .addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
viewIntent .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(viewIntent , "View"));


// Sharing
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("application/pdf");
sharingIntent.putExtra(Intent.EXTRA_STREAM, fileUri);
startActivity(Intent.createChooser(sharingIntent, "Share"));

创建/编写 PDF 文件没有问题。因此,权限似乎没有问题。共享文件(例如将其保存到 Google Drive 或通过电子邮件发送)也没有问题。因此 FileProvider 配置和 Uri 创建似乎是正确的。

那么,观看意图有什么问题呢?在模拟器中使用 API 26 进行测试时,只显示一个空白页面。在具有 API 26 的设备上运行相同代码的用户会收到一条消息,即无法访问文件(没有原因)。

但是文件存在并且访问权限不应该是问题,因为否则共享意图将无法正常工作,不是吗?

如何解决这个问题?

标签: androidandroid-fileprovider

解决方案


推荐阅读