意图在 Android N 中打开 PDF 文件

Anu*_*Anu 2 android android-intent

我一直在尝试使用 Intent 打开 PDF 文件。它适用于 Adroid N 之前的设备。以下是我使用的代码

File file = new File(gridItems.get(position).getPath());
                        Intent intent = null;
                        if (Build.VERSION.SDK_INT < 24) {
                            intent = new Intent(Intent.ACTION_VIEW);
                            intent.setDataAndType(Uri.fromFile(file), "application/pdf");
                            intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                        } else {
                            intent = new Intent();
                            intent.setAction(Intent.ACTION_VIEW);
                            Uri pdfURI = FileProvider.getUriForFile(GalleryPdfActivity.this, getApplicationContext()
                                    .getPackageName
                                            () +
                                    ".provider", file);
                            intent.putExtra(Intent.EXTRA_STREAM, pdfURI);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                            intent.setType("application/pdf");
                        }
                        try {
                            if (intent.resolveActivity(getPackageManager()) != null)
                                startActivity(intent);
                            else
                                AppUtils.toast("No Application found to open the pdf", GalleryPdfActivity.this);
                        } catch (Exception e) {
                            AppUtils.toast(e.getMessage(), GalleryPdfActivity.this);
                        }
Run Code Online (Sandbox Code Playgroud)

文件选择器打开,我选择了 Google PDF 查看器来打开应用程序。但它返回错误“无法显示 PDF(未收到文件)”。我能够在 Android N 之前的设备中打开相同的文件

Com*_*are 5

添加FLAG_GRANT_READ_URI_PERMISSIONIntent你的FileProvider情况。否则,其他应用程序无法访问该内容。请参阅文档