如何解决android 11 中的 PDF 查看器权限问题
我正在使用外部 pdf 查看器应用程序打开 pdf 文件。但是在android 11中显示eacces 权限被拒绝问题。我的清单文件中已经声明了所有权限。
<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);
请帮我解决这个问题。
解决方法
两点。
- android:requestLegacyExternalStorage="true" 在 Android 11 上被忽略。此版本的 Android 强制执行范围存储,而不管您的清单中的此标志如何,因此您可以安全地将其删除,因为它对您的设备没有影响。
- 由于强制执行范围存储,因此不允许应用访问其他应用的私有存储位置。在您的情况下,您将文件保存在 getApplicationContext().getExternalFilesDir(null).getAbsolutePath() 中,这是您的应用程序的私有位置。 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 查看器从那里访问它应该没有问题。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。