Ramakrishna Ramakrishna - 1 month ago 7
Android Question

How to download a pdf file in Android?

I want to download a pdf file from an url.
For viewing the pdf file I used the code below.

File file = new File("/sdcard/example.pdf");

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(OpenPdf.this, "No Application Available to View PDF",
Toast.LENGTH_SHORT).show();
}
}


It is working but how do I get the pdf file from an url (e.g
http://.../example.pdf
). I want to download the pdf file from this url. Please help me. Thanks in advance.

Answer

Downloading a PDF works the same as downloading any other binary file.

  1. Open a HttpUrlConnection
  2. Use the connection's getInputStream() method to read the file.
  3. Create a FileOutputStream and write the inputstream.

Check this post for example source code.

Comments