Android   发布时间:2022-04-28  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Android 文件下载三种基本方式大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

一、自己封装URLConnection 连接请求类

 public void downloadFile1() {
  try{
    //下载路径,如果路径无效了,可换成你的下载路径
    String url = "http://c.qijingonline.com/test.mkv";
    String path = Environment.getExternalStorageDirectory().getAbsolutePath();

    final long startTime = System.currentTimeMillis();
    Log.i("DOWNLOAD","startTime="+startTime);
    //下载函数
    String filename=url.substring(url.lastIndexOf("/") + 1);
    //获取文件名
    URL myURL = new URL(url);
    URLConnection conn = myURL.openConnection();
    conn.connect();
    InputStream is = conn.getInputStream();
    int fileSize = conn.getContentLength();//根据响应获取文件大小
    if (fileSize <= 0) throw new RuntimeException("无法获知文件大小 ");
    if (is == null) throw new RuntimeException("stream is null");
    File file1 = new File(path);
    if(!file1.exists()){
      file1.mkdirs();
    }
    //把数据存入路径+文件名
    FileOutputStream fos = new FileOutputStream(path+"/"+filename);
    byte buf[] = new byte[1024];
    int downLoadFileSize = 0;
    do{
      //循环读取
      int numread = is.read(buf);
      if (numread == -1)
      {
        break;
      }
      fos.write(buf,numread);
      downLoadFileSize += numread;
      //更新进度条
    } while (true);
    Log.i("DOWNLOAD","download success");
    Log.i("DOWNLOAD","totalTime="+ (System.currentTimeMillis() - startTime));
    is.close();
  } catch (Exception ex) {
    Log.e("DOWNLOAD","error: " + ex.getMessage(),ex);
  }
}

这种方式在Android 刚兴起的时候,很少下载封装框架,就自己封装了。虽然一般的文件都能下载,但这种方式缺点很多,不稳定或者各种各样的问题会出现。 

二、Android自定的下载管理(会在notification 显示下载的进度,同时可以暂停、重新连接等)

private void downloadFile2(){
  //下载路径,如果路径无效了,可换成你的下载路径
  String url = "http://c.qijingonline.com/test.mkv";
  //创建下载任务,downloadUrl就是下载链接
  DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
  //指定下载路径和下载文件名
  request.setDestinationInExternalPublicDir("",url.substring(url.lastIndexOf("/") + 1));
  //获取下载管理器
  DownloadManager downloadManager= (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
  //将下载任务加入下载队列,否则不会进行下载
  downloadManager.enqueue(request);
}

 这种方式其实就是交给了Android系统的另一个app去下载管理。这样的好处不会消耗该APP的 cpu资源。缺点是:控制起来很不灵活。

三、使用第三方 okhttp 网络请求框架

private void downloadFile3(){
  //下载路径,如果路径无效了,可换成你的下载路径
  final String url = "http://c.qijingonline.com/test.mkv";
  final long startTime = System.currentTimeMillis();
  Log.i("DOWNLOAD","startTime="+startTime);
  Request request = new Request.Builder().url(url).build();
  new OkHttpClient().newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(Call call,IOException e) {
      // 下载失败
      e.printStackTrace();
      Log.i("DOWNLOAD","download Failed");
    }
    @Override
    public void onResponse(Call call,Response response) throws IOException {
      Sink sink = null;
      BufferedSink bufferedSink = null;
      try {
        String mSDCardPath= Environment.getExternalStorageDirectory().getAbsolutePath();
        File dest = new File(mSDCardPath,url.substring(url.lastIndexOf("/") + 1));
        sink = Okio.sink(dest);
        bufferedSink = Okio.buffer(sink);
        bufferedSink.writeAll(response.body().source());
        bufferedSink.close();
        Log.i("DOWNLOAD","download success");
        Log.i("DOWNLOAD","totalTime="+ (System.currentTimeMillis() - startTime));
      } catch (Exception e) {
        e.printStackTrace();
        Log.i("DOWNLOAD","download Failed");
      } finally {
        if(bufferedSink != null){
          bufferedSink.close();
        }
      }
    }
  });
}

okhttp是一个很有名气的开源框架,目前已经很多大公司都直接使用它作为网络请求库(七牛云SDK, 阿里云SDK)。 且里面集成了很多优势,包括 okio (一个I/O框架,优化内存与cpu)。

以上所述是小编给大家介绍的Android 文件下载三种基本方式,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对编程小技巧网站的支持

大佬总结

以上是大佬教程为你收集整理的Android 文件下载三种基本方式全部内容,希望文章能够帮你解决Android 文件下载三种基本方式所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: