1

I would like to open a PDF file from my android application. I've searched how to do it in internet, and it seems very easy, but it doesn't work, at least in my mobile (Sony XPeria P).

File file = ....

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

When this code is executed, a window is opened asking to choose an application to show the PDF. When I choose the Adobe Reader, it's opened by no document is shown.

What I'm doing wrong?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Eduardo
  • 1,169
  • 5
  • 21
  • 56

3 Answers3

1

Try this, Its working for me

//Method to open the pdf file in the PDF Viewer

public void OpenPDFFile() {
    File pdfFile = new File(Environment.getExternalStorageDirectory(),"PdfFile.pdf");//File path
    if (pdfFile.exists()) //Checking for the file is exist or not
    {
        Uri path = Uri.fromFile(pdfFile);
        Intent objIntent = new Intent(Intent.ACTION_VIEW);
        objIntent.setDataAndType(path, "application/pdf");
        objIntent.setFlags(Intent. FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(objIntent);//Staring the pdf viewer
    }
}
B. Kemmer
  • 1,517
  • 1
  • 14
  • 32
Rajesh Rajaram
  • 3,271
  • 4
  • 29
  • 48
0

The setType("application/pdf") function removes all the previous data.

Jason
  • 1
  • 2
0

If the targetSdkVersion >= 24 we need to use file provider to get the Uri. See this post for details: https://stackoverflow.com/a/38858040/8192914

So, the final code would look something like this:

Uri pathUri = FileProvider.getUriForFile(getBaseContext(), context.getApplicationContext().getPackageName() + ".provider", finalFile);
Intent pdfViewerIntent = new Intent(Intent.ACTION_VIEW);
pdfViewerIntent.setDataAndType(pathUri, "application/pdf");
pdfViewerIntent.setFlags(Intent. FLAG_ACTIVITY_CLEAR_TOP);
pdfViewerIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(pdfViewerIntent);
ganjaam
  • 1,030
  • 3
  • 17
  • 29