我包含了两个要从我的应用程序中打开的PDF。他们应该使用用户安装的任何PDF查看器打开。我将PDF放在/ res / raw中。我使用了这段代码:
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);
我的filepaths.xml看起来像这样:
<paths>
<files-path path="raw/" name="raw" />
我收到一条错误消息:
java.lang.IllegalArgumentException: Failed to find configured root that contains /data/data/com.dsv2019.pvt15.prepapp/files/hjartlugnraddning.pdf
为什么会这样?
答案 0 :(得分:0)
您有一些问题。
首先,<files-path path="raw/" name="raw" />
说它为raw/
下的getFilesDir()
子目录提供文件。但是,new File(getContext().getFilesDir().getPath(), s)
将没有这样的目录,除非它以某种方式位于s
中,并且错误表明它没有。顺便说一句,您可以将其简化为new File(getContext().getFilesDir(), s)
。
第二,我认为您假设raw/
中存在一个getFilesDir()
目录。除非您创建该目录,否则它将不存在。
第三,我认为您认为原始资源是设备上的文件。他们不是。它们是开发计算机上的文件。它们只是设备上APK文件中的条目。
因此,要使其正常工作,您需要向以下代码添加代码:
从raw/
getFilesDir()
子目录
在openRawResource()
对象上使用Resources
将资源复制到该新创建的raw/
子目录中的文件
将上一步中的File
对象与FileProvider.getUriForFile()
答案 1 :(得分:-1)
您可以使用以下代码在应用内打开pdf
try {
File file = new File("your file path");
Intent intent = new Intent(Intent.ACTION_VIEW);
if (Build.VERSION.SDK_INT >= 24)
intent.setDataAndType(FileProvider.getUriForFile(PdfPageActivity.this,
BuildConfig.APPLICATION_ID + ".provider", file), "application/pdf");
else intent.setDataAndType(Uri.fromFile(file), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Intent intent1 = Intent.createChooser(intent, "Open With");
startActivity(intent1);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
它将为您提供帮助。