Android 意图打开空白 PDF,即使我使用与保存它相同的路径

Android intent opens blank PDF even though I used the same path used for saving it

我正在尝试从布局生成 PDF:

                PdfDocument document = new PdfDocument();
                PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(2480, 3508, 0).create();
                PdfDocument.Page page = document.startPage(pageInfo);

                linearview.draw(page.getCanvas());
                document.finishPage(page);

                OutputStream outStream;
                File file = new File(getExternalFilesDir(null), "pedido.PDF");

                try {
                    outStream = new FileOutputStream(file);
                    document.writeTo(outStream);
                    document.close();
                    outStream.flush();
                    outStream.close();
                    Log.d(TAG, "pdf saved to " + getExternalFilesDir(null));
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    File myPDF = new File(getExternalFilesDir(null), "pedido.PDF");
                    Uri uri = FileProvider.getUriForFile(OrderActivity.this, BuildConfig.APPLICATION_ID + ".provider", myPDF);
                    Log.d(TAG, "openPDF: intent with uri: " + uri);
                    intent.setDataAndType(uri, "application/pdf");
                    startActivity(intent);
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    Log.d(TAG, e.toString());
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    Log.d(TAG, e.toString());
                }

当我 运行 此代码时,我得到一个由默认 PDF 打开器打开的空白 PDF。我不知道它是否这样做是因为它没有找到 PDF 文件,但我猜这是问题所在,因为 PDF 已正确生成。如果我使用文件搜索器打开文件 /storage/emulated/0/Android/data/com.lucaszanella.venko/files/pedido.PDF,我会正常看到 PDF。

这是我得到的输出

D/OrderActivity: pdf saved to /storage/emulated/0/Android/data/com.lucaszanella.venko/files
D/OrderActivity: openPDF: intent with uri: content://com.lucaszanella.venko.provider/external_files/Android/data/com.lucaszanella.venko/files/pedido.PDF

如您所见,pdf 已保存到 /storage 文件夹,但 Intent 尝试从 /external_files 打开。这可能是问题所在,但我想我所做的一切都很好。

更新:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path
        name="external_files"
        path="." />
</paths>

尝试

Uri uri = Uri.fromFile(myPDF);

而不是

Uri uri = FileProvider.getUriForFile(OrderActivity.this, BuildConfig.APPLICATION_ID + ".provider", myPDF);

缺少的是:

intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

即使我不需要从外部目录读取的权限。