草庐IT

android - 打开 pdf 文件错误 : This file could not be accessed Check the location or the network and try again. Android 6 Marshmallow

coder 2023-11-29 原文

我正在尝试从外部存储中获取文件,然后我必须使用 intents 将该文件发送给 pdf 阅读器。之前下面的代码运行良好,但在安装 Android 6(Marshmallow 更新) 后,我的代码无法运行并收到 toast 消息

无法访问此文件请检查位置或网络并重试。”

(这是由于新的 android 运行时权限)。 我刚刚尝试了所有的解决方案(内容提供商等但没有工作) 任何解决方案?

 File file = new File(getFilesDir(), "myfile.pdf");
 Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file), "application/pdf");
        intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        Intent intentChooser = Intent.createChooser(intent, "Choose Pdf Application");
        try {
            startActivity(intentChooser);
        } catch (ActivityNotFoundException e) {
            //com.adobe.reader
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.adobe.reader")));
        }

最佳答案

查看以上答案后,最简单的解决方案如下。

    Uri pdf = FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".provider", file);

    Intent pdfOpenintent = new Intent(Intent.ACTION_VIEW);
    pdfOpenintent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    pdfOpenintent.setDataAndType(pdf, "application/pdf");

    try {
        startActivity(pdfOpenintent);
    } catch (ActivityNotFoundException e) {
        // handle no application here....
    }

关键是同时设置 FLAG_GRANT_READ_URI_PERMISSION 和 FLAG_ACTIVITY_CLEAR_TOP。

确保在 ApplicationManifest.xml 中声明了您的提供程序

<provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
    </provider>

她的是 provider_paths 文件

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path name="external_files" path="."/>
</paths>

关于android - 打开 pdf 文件错误 : This file could not be accessed Check the location or the network and try again. Android 6 Marshmallow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38159187/

有关android - 打开 pdf 文件错误 : This file could not be accessed Check the location or the network and try again. Android 6 Marshmallow的更多相关文章

随机推荐