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:
Use some external library to displays PDF files. Is there any that works well?
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
Opening a PDF file in Android using WebView All you need to do is just put WebView in your layout and load the desired URL by using the webView. loadUrl() function. Now, run the application on your mobile phone and the PDF will be displayed on the screen.
Find the PDF you want to open in your Files and double click to open. Select Adobe Acrobat (or whichever reader you downloaded) from the list of available options. If no list appears or the page opens in another application, you can right-click the file and select Open With to choose your PDF reader. Click Open.
Find the file manager app By far the easiest way to find downloaded files on Android is to look in your app drawer for an app called Files or My Files. Google's Pixel phones come with a Files app, while Samsung phones come with an app called My Files.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With