简体   繁体   English

使用FileProvider打开我的应用程序中包含的PDF?

[英]Using FileProvider to open PDF included in my app?

I have included two PDFs that I want to open from my app. 我已经包含了两个我想从我的应用程序打开的PDF。 They should open with whatever PDF viewer the user has installed. 它们应该打开用户安装的任何PDF查看器。 I placed the PDFs in /res/raw. 我将PDF放在/ res / raw中。 I used this code: 我用过这段代码:

File file = new File(getContext().getFilesDir().getPath(), s);
            Uri pdfUri = FileProvider.getUriForFile(getContext(), getContext().getApplicationContext().getPackageName() + ".provider", file);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(pdfUri, "application/pdf");
            intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

My filepaths.xml looks like this: 我的filepaths.xml看起来像这样:

<paths>
<files-path path="raw/" name="raw" />

I'm getting an error that says: 我收到的错误是:

java.lang.IllegalArgumentException: Failed to find configured root that contains /data/data/com.dsv2019.pvt15.prepapp/files/hjartlugnraddning.pdf

Why is this happening? 为什么会这样?

You have a few problems. 你有一些问题。

First, <files-path path="raw/" name="raw" /> says that it serves files from a raw/ subdirectory under getFilesDir() . 首先, <files-path path="raw/" name="raw" />表示它在getFilesDir()下的raw/子目录中提供文件。 However, new File(getContext().getFilesDir().getPath(), s) will not have such a directory, unless it is in s somehow, and the error suggests that it is not. 然而, new File(getContext().getFilesDir().getPath(), s)不会有这样的目录,除非是在s不知何故,并且错误表明事实并非如此。 BTW, you can simplify this as new File(getContext().getFilesDir(), s) . 顺便说一句,您可以将其简化为new File(getContext().getFilesDir(), s)

Second, I think that you are assuming the existence of a raw/ directory in getFilesDir() . 其次,我认为你假设getFilesDir()存在一个raw/目录。 Unless you create that directory, it will not exist. 除非您创建该目录,否则它将不存在。

Third, I think that you are thinking that raw resources are files on the device. 第三,我认为您认为原始资源是设备上的文件。 They are not. 他们不是。 They are files on your development machine. 它们是开发计算机上的文件。 They are just entries in the APK file on the device. 它们只是设备上APK文件中的条目。

So, to make this work, you need to add code to: 因此,要使其工作,您需要将代码添加到:

  • Create a raw/ subdirectory off of getFilesDir() getFilesDir()创建一个raw/子目录

  • Use openRawResource() on a Resources object to copy the resource to a file in that newly-created raw/ subdirectory Resources对象上使用openRawResource()Resources复制到新创建的raw/子目录中的文件

  • Use that File object from the preceding step with FileProvider.getUriForFile() 使用FileProvider.getUriForFile()执行上一步中的File对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM