在我的应用程序中显示 PDF 文件时遇到问题

Having trouble displaying PDF file in my Application

我能够使用以下代码从服务器(Web API)成功下载 PDF 文件

    HttpURLConnection connection = null;
    File file;
    File outputFile = null;
    FileOutputStream fileOutputStream = null;
    InputStream inputStream = null;
    int count;
    string filename = "xxx.pdf"
    try {
        //output path would be "/data/user/0/package.ofapplication/files/folder/"
        file = new File(interface.getFileDirectory(),"folder"); 

        if (!file.isDirectory()) file.mkdirs();

        //output would be "/data/user/0/package.ofapplication/files/folder/xxx.pdf"
        outputFile = new File(file, filename);

        URL url = new URL(getUrlMethod());
        connection = (HttpURLConnection) url.openConnection();
        connection.connect();

        int fileLength = connection.getContentLength();

        inputStream = new BufferedInputStream(url.openStream());

        fileOutputStream = new FileOutputStream(outputFile);

        .......other
        .......related
        .......downloading codes

        //this would return "/data/user/0/package.ofapplication/files/folder/xxx.pdf"
        return outputFile.getPath();
    }

现在,当我尝试使用 Android 中的以下代码查看 PDF 文件时出现错误。

// output path would be /data/user/0/package.ofapplication/files/folder/
File pdfFile = new File(pdfPath);

Intent pdfIntent = new Intent(Intent.ACTION_VIEW)
pdfIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
pdfIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

//this is the part where im getting an error
pdfIntent.setDataAndType(FileProvider.getUriForFile(this.getActivity(), this.getActivity().getApplicationContext().getPackageName() + ".provider",pdfFile), "application/pdf");

我从上面的代码中得到的错误消息是

java.lang.IllegalArgumentException: Failed to find configured root that contains /data/data/package.ofapplication/files/folder/1.pdf

有人可以帮我解决这个问题吗?我现在哭了好几个小时,但仍然找不到办法。我也试过这个 link 但我仍然有同样的错误

注:下面是我的provider_path

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>

您似乎正试图将文件存储在 internal storage 上,并将 XML 上的路径元素定义为 external storage,如 <external-path,因此请尝试更改XML 上的路径元素作为 internal storage:

<external-path

<files-path

更多信息。 https://developer.android.com/reference/android/support/v4/content/FileProvider