Android下载PDF文件

男娘i 2022-02-25 11:42 589阅读 0赞

1.下载PDF文件到本地

  1. private void downFile(String urlString){
  2. try {
  3. URL url = new URL(urlString);
  4. HttpURLConnection connection = (HttpURLConnection)
  5. url.openConnection();
  6. connection.setRequestMethod("GET");
  7. connection.setDoInput(true);
  8. connection.setDoOutput(true);
  9. connection.setUseCaches(false);
  10. connection.setConnectTimeout(5000);
  11. connection.setReadTimeout(5000);
  12. //实现连接
  13. connection.connect();
  14. if (connection.getResponseCode() == 200) {
  15. InputStream is = connection.getInputStream();
  16. //以下为下载操作
  17. byte[] arr = new byte[1];
  18. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  19. BufferedOutputStream bos = new BufferedOutputStream(baos);
  20. int n = is.read(arr);
  21. while (n > 0) {
  22. bos.write(arr);
  23. n = is.read(arr);
  24. }
  25. bos.close();
  26. String path = Environment.getExternalStorageDirectory()
  27. + "/download/";
  28. String[] name = urlString.split("/");
  29. path = path + name[name.length - 1];
  30. File file = new File(path);
  31. FileOutputStream fos = new FileOutputStream(file);
  32. fos.write(baos.toByteArray());
  33. fos.close();
  34. //关闭网络连接
  35. connection.disconnect();
  36. Log.d("下载完成","下载完成");
  37. openPDF(file);//打开PDF文件
  38. }
  39. } catch (Exception e) {
  40. // TODO: handle exception
  41. System.out.println(e.getMessage());
  42. }
  43. }

2.打开PDF文件

  1. private void openPDF(File file) {
  2. if (file.exists()) {
  3. Log.d("打开","打开");
  4. Uri path1 = Uri.fromFile(file);
  5. Intent intent = new Intent(Intent.ACTION_VIEW);
  6. intent.setDataAndType(path1, "application/pdf");
  7. intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  8. try {
  9. startActivity(intent);
  10. }
  11. catch (Exception e) {
  12. Log.d("打开失败","打开失败");
  13. }
  14. }
  15. }

3.新建一个线程调用下载方法

  1. private class MyAsyncTask extends AsyncTask<String, Void, File> {
  2. @Override
  3. protected File doInBackground(String... str) {
  4. return downFile(str[0]);//开始下载
  5. }
  6. @Override
  7. protected void onPostExecute(final File file) {
  8. //下载完成,修改UI
  9. }
  10. }

4.调用

  1. String url = "https://staticzcjb.weibangong.com/pdf/business_license.pdf";
  2. new MyAsyncTask().execute(url, null, null);

发表评论

表情:
评论列表 (有 0 条评论,589人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Android HTTP下载文件

           通过HTTP下载网络上面的文件,可以设置下载任务的优先级优先级高的先下载,允许那种网络下载,对下载任务做相应的暂停和取消。 一. 代码下载地址 [Git

    相关 Android 文件下载

    1、开启一个服务Service实现后台下载 2、通过线程池管理器实现并行下载数量控制 3、利用广播机制更新UI 4、利用网络请求库Ohttp3进行下载 创建一