始终为PDF查看器调用ActivityNotFoundException

时间:2013-12-05 07:14:34

标签: android exception pdf android-intent pdfviewer

我遇到了这个问题,我正在尝试在我的应用中打开PDF文件,如果设备上没有PDF查看器,它会重定向到Play商店以下载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阅读器的对话框。这背后的原因是什么?

2 个答案:

答案 0 :(得分:0)

试用此代码:

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();


    }

答案 1 :(得分:0)

我认为您的问题来自您的文件来源。您可以访问互联网,这样您就可以获得链接(http:// link_to_pdf),您的文件可以是本地,在这种情况下(在您的项目资源中,如{{1}例如,或在SD卡中)

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

对于网络文件,请尝试使用 google docs viewer

源代码的链接是here