且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Android中下载pdf文件?

更新时间:2023-01-30 16:42:13

下载PDF的工作方式与下载任何其他二进制文件相同。


  1. 打开 HttpUrlConnection

  2. 使用连接的 getInputStream() 方法来读取文件。

  3. 创建一个 FileOutputStream 并写入输入流。

检查这篇文章,例如源代码。 / p>

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.

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.