java - 在 Android 10 上阅读 PDF

标签 java android file file-access android-10.0

需要在 Android 10 上阅读 PDF 以下代码在 Android 9.0 上运行良好,但在 Android 10 上,负责显示 PDF 的应用程序只是闪烁并返回到我的应用程序。

            File pdfFile = new File(getExternalFilesDir(null), "Pdf");
            pdfFile.setReadable(true);
            if (pdfFile.exists()) {
                if (pdfFile.canRead()) {
                    if (pdfFile.canWrite()) {
                        Uri path = Uri.fromFile(pdfFile);
                        Intent objIntent = new Intent(Intent.ACTION_VIEW);
                        objIntent.setDataAndType(path, "application/pdf");
                        objIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                        startActivityForResult(objIntent, req_code);
                    }else{
                        Toast.makeText(MainActivity.this, "Not writable! ", Toast.LENGTH_SHORT).show();
                    }
                }else{
                    Toast.makeText(MainActivity.this, "Not readable! ", Toast.LENGTH_SHORT).show();
                }
            }else{
                Toast.makeText(MainActivity.this, "The file does not exists! ", Toast.LENGTH_SHORT).show();
            }

在 onActivityResult 方法上,我收到 RESULT_CANCELED 作为 result_code 和 data == null。

最佳答案

The following code works fine on Android 9.0

您项目中的某人做了一些不幸的事情,让该代码在 Android 9 上运行。三年前,从 Android 7.0 开始,它就应该失败,并出现 FileUriExposedException

在 Android 10 上,除了少数特定于应用程序的有限位置之外,应用程序无法访问外部存储。这就是 Google 从 Android 7.0 开始发出的警告,即您不应再使用 Uri.fromFile()

三年前的正确解决方案以及今天的正确解决方案是 use FileProvider使该 PDF 可用于 PDF 查看器应用程序。

另请参阅:

关于java - 在 Android 10 上阅读 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59505576/

相关文章:

java - Java 中将多个字符串分组为一个通用字符串

java - Spring boot Autowired 存储库不适用于 SpringRunner 和 JPA 数据

Android - 双击WebView检测

android - LibGdx resolutionFileResolver + Assetmanager,文件名?

json - 如何解析正在处理的 JSON 文件

c# - 从目录中获取 x 个最新文件

java - Lombok @Wither/@With Inheritance(超/子类)

android - 如何在 Android 中使用 Espresso 为 textview 设置值

python - 在python中将文件作为两个单独的部分打开

java - TextView 中的文本在滚动时淡出