使用Retrofit下载文件并实现进度监听的示例
1.前言
最近要做一个带进度条下载文件的功能,网上看了一圈,发现好多都是基于OkHttpClient添加拦截器来实现的,个人觉得略显复杂,所以还是采用最简单的方法来实现:基于文件写入来进行进度的监听。
2.实现步骤
2.1设计监听接口
根据需求设计一下接口:
publicinterfaceDownloadListener{
voidonStart();//下载开始
voidonProgress(intprogress);//下载进度
voidonFinish(Stringpath);//下载完成
voidonFail(StringerrorInfo);//下载失败
}
如果还需下载速度等等,可以自行设计接口和参数。
2.2编写网络接口Service
publicinterfaceDownloadService{
@Streaming
@GET
Calldownload(@UrlStringurl);
}
跟正常接口写法基本一致,需要注意的是要添加@Streaming注解。
默认情况下,Retrofit在处理结果前会将服务器端的Response全部读进内存。如果服务器端返回的是一个非常大的文件,则容易发生oom。使用@Streaming的主要作用就是把实时下载的字节就立马写入磁盘,而不用把整个文件读入内存。
2.3开始网络请求
publicclassDownloadUtil{
publicstaticvoiddownload(Stringurl,finalStringpath,finalDownloadListenerdownloadListener){
Retrofitretrofit=newRetrofit.Builder()
.baseUrl("http://www.xxx.com")
//通过线程池获取一个线程,指定callback在子线程中运行。
.callbackExecutor(Executors.newSingleThreadExecutor())
.build();
DownloadServiceservice=retrofit.create(DownloadService.class);
Callcall=service.download(url);
call.enqueue(newCallback(){
@Override
publicvoidonResponse(@NonNullCallcall,@NonNullfinalResponseresponse){
//将Response写入到从磁盘中,详见下面分析
//注意,这个方法是运行在子线程中的
writeResponseToDisk(path,response,downloadListener);
}
@Override
publicvoidonFailure(@NonNullCallcall,@NonNullThrowablethrowable){
downloadListener.onFail("网络错误~");
}
});
}
}
在Retrofit中,Callback默认运行在主线程中,如果我们直接将Response写到磁盘这一操作直接运行在主线程中,会报NetworkOnMainThreadException异常。所以必须放在子线程中去运行。
目前为止,都还是一个很正常的网络请求。所以,还是很简单的。下面重头戏来了。
2.4监听下载进度
privatestaticvoidwriteResponseToDisk(Stringpath,Responseresponse,DownloadListenerdownloadListener){ //从response获取输入流以及总大小 writeFileFromIS(newFile(path),response.body().byteStream(),response.body().contentLength(),downloadListener); } privatestaticintsBufferSize=8192; //将输入流写入文件 privatestaticvoidwriteFileFromIS(Filefile,InputStreamis,longtotalLength,DownloadListenerdownloadListener){ //开始下载 downloadListener.onStart(); //创建文件 if(!file.exists()){ if(!file.getParentFile().exists()) file.getParentFile().mkdir(); try{ file.createNewFile(); }catch(IOExceptione){ e.printStackTrace(); downloadListener.onFail("createNewFileIOException"); } } OutputStreamos=null; longcurrentLength=0; try{ os=newBufferedOutputStream(newFileOutputStream(file)); bytedata[]=newbyte[sBufferSize]; intlen; while((len=is.read(data,0,sBufferSize))!=-1){ os.write(data,0,len); currentLength+=len; //计算当前下载进度 downloadListener.onProgress((int)(100*currentLength/totalLength)); } //下载完成,并返回保存的文件路径 downloadListener.onFinish(file.getAbsolutePath()); }catch(IOExceptione){ e.printStackTrace(); downloadListener.onFail("IOException"); }finally{ try{ is.close(); }catch(IOExceptione){ e.printStackTrace(); } try{ if(os!=null){ os.close(); } }catch(IOExceptione){ e.printStackTrace(); } } }
所以,实际就是通过监听文件的写入来实现进度的监听。
2.5使用例子
Stringurl="";
Stringpath="";
DownloadUtil.download(url,path,newDownloadListener(){
@Override
publicvoidonStart(){
//运行在子线程
}
@Override
publicvoidonProgress(intprogress){
//运行在子线程
}
@Override
publicvoidonFinish(Stringpath){
//运行在子线程
}
@Override
publicvoidonFail(StringerrorInfo){
//运行在子线程
}
});
注意,上面的回调都是运行在子线程中。如果需要更新UI等操作,可以使用Handler等来进行更新。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。