Opening pdf file programmatically is going into me

2019-02-15 21:29发布

问题:

How come every time i try to open a pdf file in my SDCARD using the following code, it doesn't actually open the pdf file itself, but goes into the menu of adobe reader? Is there anything wrong with my code?

Intent intent = new Intent();
    File pdfFile = new File("/sdcard/sample.pdf");
    Uri path = Uri.fromFile(pdfFile);
    intent.setAction(Intent.ACTION_VIEW); 
    intent.setData(path);
    intent.setType("application/pdf");
    intent.setPackage("com.adobe.reader");
    startActivity(intent);

回答1:

No, there's nothing wrong. You've set the type to pdf and specified the package as adobe.reader. What that does is fire off an intent to launch the pdf in adobe reader. There's no way to display a pdf directly in your app without using a library (or writing code yourself) to render PDFs and display them.

Note that if you only set the type and not the package, the system will find whatever app is available to display PDFs

EDIT

You can try something like

    Intent intent = new Intent(Intent.ACTION_VIEW);
    File file = new File( filename  );
    intent.setDataAndType( Uri.fromFile( file ), "application/pdf" );
    startActivity(intent);

or

        Intent intent = new Intent();
        intent.setPackage("com.adobe.reader");
        intent.setDataAndType(Uri.fromFile(file), "application/pdf");
        startActivity(intent);


回答2:

Here I am giving my pdf file name. You give your file name.

    private static String FILE = Environment.getExternalStorageDirectory().getPath()+"/TestPDF.pdf";   

    File file = new File(FILE);

    if (file.exists()) {
        Uri path = Uri.fromFile(file);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(path, "application/pdf");
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        try {
            startActivity(intent);
        } 
        catch (ActivityNotFoundException e) {
            Toast.makeText(this, 
                "No Application Available to View PDF", 
                Toast.LENGTH_SHORT).show();
        }
    }