在Android Nougat中打开时显示空白屏幕的PDF文件

问题描述 投票:8回答:3

我正在创建一个PDF文件并将其保存在本地存储中。当试图打开它时,它在除了Android N之外的所有设备中都是完美的。我可以使用FileProvider在Android N中打开PDF文件,但它显示为空白。

这是我的URI

content://com.products.provider/external_storage_root/Android/data/com.products/in_17052017_170502_1_1001.pdf

这是我的代码

Uri path;

File pdfFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/"
                + "Android" + "/" + "data" + "/" + "com.products" + "/" + file);

if (Build.VERSION.SDK_INT >= 24) {
            path = FileProvider.getUriForFile(getActivity(), "com.products.provider", pdfFile);
        } else {
            path = Uri.fromFile(pdfFile);
        }

        // Setting the intent for pdf reader
        Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
        pdfIntent.setDataAndType(path, "application/pdf");
        pdfIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        pdfIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

        try {
            startActivity(pdfIntent);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(getActivity(), "Can't read pdf file", Toast.LENGTH_SHORT).show();
        }
android android-fileprovider android-pdf-api
3个回答
35
投票

问题在于如何在intent上设置标志

pdfIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

相反,试试这个:

pdfIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
pdfIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

6
投票

Grzegorz Matyszczak的解决方案适用于我的案例。我和Sabya Sachi的设置非常相似。更具体地说,这一行允许我看到PDF文件(来自FileProvider.getURIForFile调用的URI):

pdfIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

有关grantUriPermissions here的更多信息,请参阅android:grantUriPermissions部分。


3
投票

我可以看到你使用FileProvider作为Nougat。您必须在AndroidManifest.xml中添加FileProvider标记。

<provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.mydomain.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
</provider>

FileProvider只能为您事先指定的目录中的文件生成内容URI。要将此文件链接到FileProvider,请添加元素作为定义FileProvider的元素的子元素。

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

您必须为每个目录指定一个子元素,该目录包含您想要内容URI的文件。您可以将它们添加到名为res/xml/file_paths.xml的新文件中。例如,这些XML元素指定两个目录:

<paths  xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path name="my_images" path="images/"/>
    <files-path name="my_docs" path="docs/"/>
</paths>

- >你必须在file_paths.xml中设置你的PDF目录路径

有关更多详细信息,请参阅this

© www.soinside.com 2019 - 2024. All rights reserved.