始终为PDF Viewer调用ActivityNotFoundException



我在应用程序中打开PDF文件时遇到了这个问题,如果设备上没有PDF查看器,它会重定向到Play Store下载Adobe Reader。然而,我已经下载了Adobe Reader,它仍然捕获ActivityNotFoundException

这是我的代码:

            Uri uri = Uri.parse(pdfUrl);
            intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(uri, "application/pdf");
            intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            try {
                startActivity(intent);
            } catch (ActivityNotFoundException e) {
                // No application to view, ask to download one
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("No Viewer");
                builder.setMessage("Download PDF Viewer?");
                builder.setPositiveButton(getString("Okay"),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                Intent innerIntent = new Intent(
                                        Intent.ACTION_VIEW);
                                innerIntent.setData(Uri
                                        .parse("market://details?id=com.adobe.reader"));
                                startActivity(innerIntent);
                            }
                        });
                builder.setNegativeButton("Cancel"), null);
                builder.create().show();
            }

我已经下载了Adobe阅读器,下次运行该应用程序时,它仍然会提示我下载PDF Viewer的对话框。这背后的原因是什么?

试试这个代码:

try {

                PackageManager packageManager = getActivity()
                        .getPackageManager();
                Intent testIntent = new Intent(Intent.ACTION_VIEW);
                testIntent.setType("application/pdf");
                List<?> list = packageManager.queryIntentActivities(testIntent,
                        PackageManager.MATCH_DEFAULT_ONLY);
                if (list.size() > 0 && file.isFile()) {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    Uri uri = Uri.fromFile(file);
                    intent.setDataAndType(uri, "application/pdf");
                    startActivity(intent);
                } else {
            Toast.makeText(this, "PDF Reader application is not installed in your device", Toast.LENGTH_LONG)
                .show();
                    }
                }
            } catch (NullPointerException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();

    }

我认为您的问题来自于文件的来源。您可以在互联网上,因此您有一个链接(http://link_to_pdf),您的文件可以是本地,在这种情况下(例如,在asset等项目资源中或SD卡中)

建议您现在使用的代码用于SD卡上的本地文件或物理设备中的本地文件。

对于web文件,请尝试使用谷歌文档查看器

源代码的链接在这里

最新更新