5

I have an App that downloads a PDF file and stores it with MODE_PRIVATE (for security purposes) on the Internal Memory of the App:

FileOutputStream fos = getApplicationContext().openFileOutput(LOCAL_FILE_NAME, Context.MODE_PRIVATE);

InputStream inputStream = entity.getContent();
byte[] buffer = new byte[1024];
int bufferLength = 0; 

while((bufferLength = inputStream.read(buffer)) > 0) {           
  fos.write(buffer, 0, bufferLength);      
}

fos.close();

How can I open and display the downloaded PDF file? I have been searching in StackOverflow and I haven't found a clear solution for this.

It seems that the problem is that Android doesn't has native support to open PDF files, so I think that there are two options:

  1. Use some external library to displays PDF files. Is there any that works well?

  2. Launch an Intent to show the PDF file, but it seems that the files stored as MODE_PRIVATE can't be opened by external Apps. I have found some solutions that copies the file to the external memory and then launches the Intent, but this procedure breaks the security purpose of the MODE_PRIVATE option, right?

Thanks for reading

Spike777
  • 227
  • 5
  • 12

2 Answers2

11

How can I open and display the downloaded PDF file?

Create a ContentProvider to serve the PDF file, then use an ACTION_VIEW Intent with the Uri to your ContentProvider to open it in the user's chosen PDF viewer.

This sample project demonstrates how to serve a PDF file from internal storage.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Thanks for your answer CommonsWare, this solution works with files saved as MODE_PRIVATE ? – Spike777 Jan 14 '13 at 22:02
  • Once you're serving files through a `ContentProvider`, how or where you store the file doesn't really matter anymore. As long as the PDF Viewer supports the `content://` scheme, you're good to go. All the proper ones, DO. – 323go Jan 14 '13 at 22:04
  • @Spike777: "this solution works with files saved as MODE_PRIVATE?" -- yes. Files are `MODE_PRIVATE` by default, and the sample project I linked to works. – CommonsWare Jan 14 '13 at 22:21
1

To make a file from internal storage available to other apps the cleanest approach is to use a content provider. Luckily, Android comes with FileProvider – an implementation that might just serve your needs. You don't need to implement code (contrary to the approach of @CommonsWare), you just need to specifiy the provider in your manifest.

Peter F
  • 3,633
  • 3
  • 33
  • 45