RXJAVA2 and Retrofit2 are used more and more recently in the encapsulation of a common network request library, which includes a single file download method, so this is recorded here. Demo at the end of the article
Because many of the methods on the Internet are using interceptors to monitor progress, the personal feel that the use of very complex and, so took a coincidence, in the file written to the hard disk when the file read and write to listen to, solve the retrofit2 download file no progress monitoring problems.
The use code after the first package, use simple, directly callback the downloaded file
Encapsulation steps
- 1. Define the interface (when using the full URL, @Streaming annotations can be used to download large files)
@Streaming @GET Observable<ResponseBody> downLoadFile (@NonNull @Url String Url);
- 2. File download callback method and File Save method
Public Abstract classFiledownloadobserver<t> extends Defaultobserver<t>{@Override Public voidOnNext (T t) {ondownloadsuccess (t); } @Override Public voidOnError (Throwable e) {ondownloadfail (e); } //can be overridden, specifically implemented by subclasses@Override Public voidOnComplete () {}//Download a successful callback Public Abstract voidondownloadsuccess (T t); //Download Failure callback Public Abstract voidOndownloadfail (Throwable throwable); //Download Progress monitoring Public Abstract voidOnProgress (intProgressLongTotal ); /** * Write files to local * @param responsebody request results * @param destfiledir target folder * @param destfilename target file name * @return Write completed file * @throws IOException IO exception*/ PublicFile saveFile (responsebody responsebody, String destfiledir, String destfilename) throws IOException {INPUTST Ream is=NULL; byte[] buf =New byte[2048]; intLen =0; FileOutputStream Fos=NULL; Try { is=Responsebody.bytestream (); FinalLongTotal =responsebody.contentlength (); Longsum =0; File dir=NewFile (Destfiledir); if(!dir.exists ()) {Dir.mkdirs (); } File File=NewFile (dir, destfilename); FOS=Newfileoutputstream (file); while(len = is. Read (BUF))! =-1) {sum+=Len; Fos.write (BUF,0, Len); FinalLongFinalsum =sum; //This is the monitoring callback for the progress.OnProgress ((int) (Finalsum * -/Total) ; } fos.flush (); returnfile; } finally { Try { if( is!=NULL) is. Close (); } Catch(IOException e) {e.printstacktrace (); } Try { if(Fos! =NULL) Fos.close (); } Catch(IOException e) {e.printstacktrace (); } } }}
/** * Download Single file, this method does not support breakpoint download * * @param URL file address * @param destDir Storage Folder * @ param filename Store file name * @param filedownloadobserver Listener Callback*/ Public voidDownloadFile (@NonNull string url, final string destDir, final string fileName, final filedownloadobserver<file>filedownloadobserver) {Retrofit Retrofit=NewRetrofit.builder (). Client (Newokhttpclient ()). BASEURL (Base_api. Base_url). Addcalladapterfactory (Rxjava2calladapterfactory.create ()). Addconverterfactory (Gs Onconverterfactory.create ()). build (); Retrofit. Create (Base_api.class). DownLoadFile (URL). Subscribeon (Schedulers.io ())//Subscribeon and Obseron must be in the IO thread if an error occurs on the main thread. Observeon (Schedulers.io ()). Observeon (Schedulers.computation () )//need to. Map (NewFunction<responsebody, file>() {@Override PublicFile Apply (@NonNull responsebody responsebody) throws Exception {returnfiledownloadobserver.savefile (Responsebody, DestDir, fileName); }}). Observeon (Androidschedulers.mainthread ()). Subscribe (Filedownloadobserv ER); }
- 4 use, as a starting figure
DownloadFile ("File Download URL","Destination Storage Path","file name",NewFiledownloadobserver<file>() {@Override Public voidondownloadsuccess (file file) {} @Override Public voidOndownloadfail (Throwable throwable) {} @Override Public voidOnProgress (intProgressLongTotal ) { } });
Android rxjava2+retrofit2 Single File download monitor progress Package