この記事では、参照用のRXJAVA実装ダウンロードファイルの特定のコードを共有しています。特定のコンテンツは次のとおりです
この記事では、Retrofit + rxjavaを使用しています
1.導入:
// rxjavaコンパイル 'io.reactivex:rxjava:ribrot.release' compile 'io.reactivex:rxandroid:rxandroid' // network -squareup compile 'com.squareup.retrofit2:Retrofit:restary.Release' com.retrease 'com.squareup.retrofit2:adapter-rxjava:latest.release' compile 'com.squareup.okhttp3:okhttp:rester.release' compile 'com.squareup.okhttp3:logging-interceptor:latest.release' compile 'com.squareup.htpries
2。ダウンロード進行状況の監視を増やす:
public interface downloadprogressListener {void update(long bytesread、long contentlength、boolean done);} public class downloadprogressResponseBodyはresponsebodyを拡張します{private responsbody responsebody;プライベートダウンロードprogristener progressListener; Private BufferedSource BufferedSource; public downloadprogressResponseBody(ResponseBody body、downloadProgressListener ProgressListener){this.responsebody = responsebody; this.progressListener = ProgressListener; } @Override public mediatype contentType(){return Responsebody.contentType(); } @Override public long contentlength(){return ressonsbody.contentlength(); } @Override public bufferedSource source(){if(bufferedsource == null){bufferedsource = okio.buffer(source(responsbody.source())); } return bufferedsource; } private source source(source source){return new ForwardingSource(source){long totalbytesRead = 0L; @Override public long read(バッファシンク、ロングバイテクター)スローioException {long bytesRead = super.read(sink、bytecount); // read()このソースが使い果たされている場合は、read()readの数を返します。 TotalByTesRead += bytesRead!= -1? BytesRead:0; if(null!= progressListener){progressListener.update(totalbytesRead、responsebody.contentlength()、bytesRead == -1); } bytesReadを返します。 }}; }} public class downloadprogressInterceptor Interceptor {private downloadprogressListenerリスナー; public downloadprogressInterceptor(downloadprogressListenerリスナー){this.listener = listener; } @Override public Response Intercept(チェーンチェーン)IoExceptionをスロー{response originalResponse = Chain.proceed(Chain.Request()); return originalResponse.newBuilder().body(new downloadprogressResponseBody(originalResponse.body()、listener)).build(); }}3.ダウンロードの進行状況のために要素クラスを作成します:
パブリッククラスのダウンロード実装{private int progress;プライベートの長い電流式;プライベートの長いTotalFilesize; public int getProgress(){return progress; } public void setProgress(int progress){this.progress = progress; } public long getCurrentFilesize(){return currentFilesize; } public void setCurrentFilesize(long currentFilesize){this.CurrentFilesize = currentFilesize; } public long getTotalFilesize(){return totalFilesize; } public void settoTotalFileSize(long totalfilesize){this.totalfilesize = totalfilesize; } @override public int descrationeContents(){return 0; } @Override public void writeToparcel(Parcel Dest、int Flags){dest.writeint(this.progress); dest.writelong(this.currentfilesize); dest.writelong(this.totalfilesize); } public download(){} protected download(Parcel in){this.progress = in.readint(); this.currentfilesize = in.readlong(); this.totalfilesize = in.readlong(); } public static final parcelable.creator <download> creator = new Parcelable.creator <download>(){@Override public download createfromparcel(parcel source){return new download(source); } @override public download [] newArray(int size){return new download [size]; }};}4。ファイルネットワーククラスをダウンロードしてください:
パブリックインターフェイスdownloadService {@Streaming @get Observable <ResponseBody>ダウンロード(@URL String URL);}注:@urlは完全なダウンロードURLです。インターセプトなし
public class downloadapi {private static final string tag = "downloadapi";プライベート静的最終int default_timeout = 15;パブリックレトロフィットレトロフィット。 public downloadapi(string url、downloadprogresslistenerリスナー){downloadprogressInterceptor interceptor = new downloadProgressInterceptor(リスナー); okhttpclient client = new okhttpclient.builder().addinterceptor(interceptor).retryonconnectionfailure(true).connecttimeout(default_timeout、timeunit.seconds).build(); RETROFIT = new RETROFIT.BUILDER().BASEURL(url).Client(client).addcalladapterfactory(rxjavacalladapterfactory.create()).build(); } public void downloadapk(@nonnull string url、final file、subscriber subscriber){log.d(tag、 "downloadapk:" + url); RETROFIT.CREATE(DownloadService.Class).DownLoad(URL).Subscribeon(Schedulers.io()).Unsubscribeon(Schedulers.io()).Map(new Func1 <responsebody、inputstream>(){@override public inputstream call(Responsedbodybody) .observeon(schedulers.computation()).doonnext(new Action1 <InputStream>(){@Override public call(inputstream inputstream){try {fileutils.writefile(file);} catch(ioexception e){e.printstrace() .observeon(androidschedulers.mainthread()).subscribe(subscriber); }}それからそれは呼ばれます:
ネットワークはサービスで行われます
Public Class DownloadService拡張Intentservice {private static final string tag = "downloadService"; Private NotificationCompat.Builder NotificationBuilder; Private NotificationManager NotificationManager; private string apkurl = "http://download.fir.im/v2/app/install/595c5959959d6901ca0004ac?download_token=1a9dfa8f248b6e45ea46bc5ed96a0a9e&ruse -ce -= update"; public downloadService(){super( "downloadService"); } @Override Protected void onhandleintent(Intent Intent){notificationManager =(NotificationManager)getSystemService(Context.Notification_Service); NotificationBuilder = new NotificationCompat.Builder(this).Setsmallicon(r.mipmap.ic_download).setContentTitle( "download").setContentText( "file").setautocancel(true); NotificationManager.Notify(0、notificationBuilder.build());ダウンロード(); } private void download(){downloadprogressListenerリスナー= new downloadProgressListener(){@Override public void usdutt(long bytesread、long contentlength、boolean done){ダウンロード= new download(); download.settotalfilesize(contentlength); download.setCurrentFilesize(bytesRead); int progress =(int)((bytesread * 100) / contentlength); download.setProgress(Progress); SendNotification(ダウンロード); }}; file outputFile = new file(Environment.getExternalStoragePublicDirectory(Environment.Directory_Downloads)、 "file.apk"); string baseurl = stringutils.gethostname(apkurl); new Downloadapi(baseurl、リスナー).downloadapk(apkurl、outputfile、new subscriber(){@Override public void oncompleted(){downloadcompleted();} @override public void onerror(throwable e){e.printstacktrace( e.getMessage()); } private void downloadcompleted(){ダウンロード= new download(); download.setProgress(100); SendIntent(ダウンロード); NotificationManager.Cancel(0); NotificationBuilder.setProgress(0、0、false); notificationbuilder.setContentText( "ファイルダウンロード"); NotificationManager.Notify(0、notificationBuilder.build()); } private void sendnotification(ダウンロードダウンロード){sendintent(download); notificationBuilder.setProgress(100、download.getProgress()、false); notificationBuilder.setContentText(stringutils.getDatasize(download.getCurrentFilesize()) + "/" + stringutils.getDatasize(download.getTotalFilesize())); NotificationManager.Notify(0、notificationBuilder.build()); } private void sendIntent(ダウンロードダウンロード){Intent Intent = new Intent(mainActivity.message_progress); intent.putextra( "download"、download); localbroadcastmanager.getInstance(downloadservice.this).sendbroadcast(intent); } @Override public void ontaskRemoved(Intent rootintent){notificationmanager.cancel(0); }}MainActivityコード:
パブリッククラスのMainActivityは、AppCompatActivityを拡張します{public static final string message_progress = "message_progress";プライベートAppCompatButton btn_download;プライベートな進行状況の進行。 Private TextView Progress_Text; private BroadCastReceiver BroadCastreCeiver = new BroadCastReceiver(){@Override public void onreceive(Context Context、Intent Intent){if(intent.getAction()。 Progress.setProgress(download.getProgress()); if(download.getProgress()== 100){progress_text.settext( "ファイルダウンロードComplete"); } else {progress_text.settext(stringutils.getDatasize(download.getCurrentFilesize()) + "/" + stringutils.getDatasize(download.getTotalFilesize()); }}}}}}}; @Override Protected void oncreate(bundle savedinstancestate){super.oncreate(savedinstancestate); setContentView(r.layout.activity_main); btn_download =(appcompatbutton)findviewbyid(r.id.btn_download); Progress =(ProgressBar)FindViewByID(R.ID.Progress); Progress_text =(textView)findViewByID(r.id.progress_text); RegisterReceiver(); btn_download.setonclicklistener(new View.onclickListener(){@Override public void onclick(View View){Intent Intent = new Intent(mainActivity.、downloadservice.class); startservice(intent);}}); } private void Registerreceiver(){localBroadCastmanager bmanager = localbroadcastmanager.getInstance(this); IntentFilter IntentFilter = new IntentFilter(); intentfilter.addaction(message_progress); bmanager.registerreceiver(broadcastreceiver、intentfilter); }}この記事のソースコード:RXJAVAの実装ダウンロードファイルをRETOFIT RXJAVA
上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。