当前位置: 移动技术网 > IT编程>移动开发>Android > Android 文件下载三种基本方式

Android 文件下载三种基本方式

2019年07月24日  | 移动技术网IT编程  | 我要评论

大剑17,会议系统主机,死神594

一、自己封装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, 0, 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 文件下载三种基本方式,希望对大家有所帮助

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网