【发布时间】:2020-04-20 10:41:42
【问题描述】:
在我的应用程序中,我正在将 pdf 下载到下载文件夹,并尝试使用以下代码打开。
String FileName="CardsDecks";
File imagePath = new File(this.getFilesDir(), "Download");
File newFile = new File(imagePath, FileName+ ".pdf");
Uri contentUri = FileProvider.getUriForFile(this, "com.cards.mycards.fileprovider", newFile);
Intent intent =new Intent(Intent.ACTION_VIEW)
.setDataAndType(contentUri, "application/pdf")
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Intent intent1 = Intent.createChooser(intent, "Open File");
startActivity(intent1);
清单文件中的提供者定义
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.cards.mycards.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
provider_paths.xml
<paths>
<files-path name="CardsDecks" path="." />
</paths>
该应用程序仅显示驱动器 pdf 查看器和打开文件的单词选项,而不是手机中存在的 pdf 查看器。
当我点击驱动器 pdf 查看器时,它会立即打开和关闭。我已经检查了下载文件夹中的文件,文件在那里,里面有内容。
请在上面提供帮助。
【问题讨论】:
-
检查您是否能够解决意图。对于多个选择,您可以尝试创建一个意图选择器。 stackoverflow.com/a/17453242/4694013
-
嗨 Anoop,在那个链接中提到的代码不适用于 AndroidX 我收到此错误 android.os.FileUriExposedException: file:///storage/emulated/0/CardsDecks .pdf 通过 Intent.getData() 暴露在应用之外
-
setFlags覆盖addFlags。 -
对于 androidx 我写过这样的... Uri contentUri = FileProvider.getUriForFile(this, "com.cards.mycards.fileprovider", imagePath); Intent intent = new Intent(Intent.ACTION_VIEW) .setDataAndType(Uri.fromFile(imagePath), "application/pdf") .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);开始活动(意图);但我收到错误 java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/Download/CardsDecks.pdf
-
嗨 StenSoft,我已删除 setflags
Uri contentUri = FileProvider.getUriForFile(this, "com.cards.mycards.fileprovider", imagePath); Intent intent = new Intent(Intent.ACTION_VIEW) .setDataAndType(Uri.fromFile(imagePath), "application/pdf") .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);但我收到错误 java.lang.IllegalArgumentException: 无法找到包含 /storage/emulated/0/Download 的已配置根/CardsDecks.pdf
标签: java android android-pdf-api androidpdfviewer