android - Android 11 中的 PDF 查看器权限问题

标签 android android-permissions android-external-storage android-fileprovider accessibility

我正在使用外部 pdf 查看器应用程序打开 pdf 文件。但在android 11中显示eacces 权限被拒绝的问题。我的 list 文件中已声明所有权限。

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
        <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
        

还声明了这一点:

android:requestLegacyExternalStorage="true"

使用以下代码创建和编写内容:

byte [] decodedContent = Base64.decode(base64.getBytes(), Base64.DEFAULT);

                try {

                    File pdfDirPath = new File(getApplicationContext().getExternalFilesDir(null).getAbsolutePath(), "pdfs");
                    File file5 = new File(pdfDirPath, globalData.getVin()+".pdf");

                    if (!file5.exists()) {

                        file5.getParentFile().mkdirs();
                    }

                    outputStream = new FileOutputStream(file5);
                    outputStream.write(Base64.decode(base64, Base64.NO_WRAP));
                    outputStream.close();
               

并像这样打开上面的文件:

    Uri   path = FileProvider.getUriForFile(getApplicationContext(), getApplicationContext().getPackageName() + ".helper.ProviderClass", file5);
  intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(path, "application/pdf");
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

请帮我解决这个问题。

最佳答案

两点。

  1. android:requestLegacyExternalStorage="true"在 Android 11 上会被忽略。无论 list 中是否有此标志,此版本的 Android 都会强制执行范围存储,因此您可以安全地将其取出,因为它对您的设备没有影响。
  2. 由于强制执行范围存储,因此不允许应用访问其他应用的私有(private)存储位置。在您的情况下,您将文件保存在 getApplicationContext().getExternalFilesDir(null).getAbsolutePath() 中,这是您应用程序的私有(private)位置。 Android 11 上的范围存储规则将禁止您的外部 PDF 查看器应用打开应用所在位置中的任何文件。 在 Android 11 上,如果您希望其他应用打开您的应用创建的文档,您至少有两个选择,甚至可能更多。

a) 一个复杂的问题。使用 FileProvider https://developer.android.com/reference/androidx/core/content/FileProvider

b) 这个要简单得多。由于您的目的是与其他应用程序共享此文件,因此您应该使用 MediaStore API 并将其写入 MediaStore.Downloads.EXTERNAL_CONTENT_URI,而不是写入应用程序的特定目录。网上有很多很好的例子,例如 How to save pdf in scoped storage? 您的 PDF 查看器从那里访问它应该没有问题。

关于android - Android 11 中的 PDF 查看器权限问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66373415/

相关文章:

安卓 WebView : Does loading from resources still require Internet permissions?

java - 在 Android 中以编程方式运行 shell 命令需要什么权限?

android - 从图库中读取位图并将其写入 SD 卡失败

android - SQLite 插入顺序与查询顺序?

android - 来自 Android App 的 wp v2 rest 请求过载 CPU 使用率

android - 使用 osmdroid 的夜间模式

android - 无法在 TabLayout 设计支持库中看到 Tab Indicator

java - 应用程序在选择图像时崩溃

android - 检查是否为另一个应用程序授予了外部存储管理器

android -/sdcard/emulated/0 和/sdcard 之间的差异