【问题标题】:PDF opens and closes immediatelyPDF 立即打开和关闭
【发布时间】: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,我已删除 setflagsUri 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


【解决方案1】:

尝试:

Uri excelPath = FileProvider.getUriForFile(this, getApplicationContext().getPackageName()+ ".provider", newFile);

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 2022-11-14
  • 1970-01-01
  • 2018-11-09
  • 1970-01-01
  • 1970-01-01
  • 2017-06-06
  • 2016-11-09
  • 2017-08-20
  • 2017-11-21
相关资源
最近更新 更多