正在尝试打开 pdf 文件 Android

Trying to open pdf file Android

我遇到了这个错误:

E/AndroidRuntime: java.lang.IllegalArgumentException: Failed to find configured root that contains /data/data/com.mobgen.androidinterviewtest/files/LaFerrari.pdf
E/AndroidRuntime:     at android.support.v4.content.FileProvider$SimplePathStrategy.getUriForFile(FileProvider.java:678)
E/AndroidRuntime:     at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:377)
E/AndroidRuntime:     at com.mobgen.interview.SingleCarActivity.onClick(SingleCarActivity.java:92)

是因为这行代码:

Uri uri = FileProvider.getUriForFile(SingleCarActivity.this, "be.myapplication", file);

我已按照找到的资源进行操作: http://developer.android.com/reference/android/support/v4/content/FileProvider.html

Open file in cache directory with ACTION_VIEW

How to use support FileProvider for sharing content to other apps?

但是我仍然无法解决我遇到的错误。

下面你可以看到我的代码:

SingleCarActivity.java:

File file = new File(getFilesDir(), pdf); //pdf contains "LaFerrari.pdf"
Uri uri = FileProvider.getUriForFile(SingleCarActivity.this, "be.myapplication", file);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);

AndroidManifest.xml:

<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="be.myapplication"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>

file_paths.xml:

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path name="my_pdf" path="assets/"/>
</paths>

下面你可以看到我的项目结构的截图: Link: http://i.imgur.com/4dbhcKF.png

FileProvider 无法直接提供资产,因为资产不是文件。您的主要选择是:

  1. 将资产复制到一个文件,位于您为 FileProvider 配置的位置。我在 this sample app, but the answers to the question from your comment 中演示了那种 FileProvider 配置,用于将资产复制到文件的基础知识。

  2. 使用my StreamProvider,可以直接提供资源,无需制作副本。