이 기사에서는 참조에 대한 RXJava 구현 다운로드 파일의 특정 코드를 공유합니다. 특정 내용은 다음과 같습니다
이 기사는 다음을 사용합니다. Retrofit + rxjava
1. 소개 :
// rxjava compile 'io.reactivex : rxjava : 최신. rxjava'compile 'io.reactivex : rxandroid : rxandroid : rxandroid : rxandroid : rxandroid : rxandroid : com.squareup.retrofit2 : retrofit : retrofit'com.squareup.retrofit2 : retofit. 'com.squareup.retrofit2 : Adapter-rxjava : 최신. release'compile 'com.squareup.okhttp3 : okhttp : elest.release'com.squareup.okhttp3 : logging-interceptor : elease.squareup.okhttp3 : logging-infortor : logging-inferease.
2. 다운로드 진행 상황 모니터링 증가 :
public Interface downloadProgressListener {void update (long bytesread, long contentlength, boolean done);} 공개 클래스 DownloadProgressResponseBody 확장 응답 바디 {Private ResponskBody ResponseBody; Private DownloadProgressListener ProgressListener; Private BufferedSource BufferedSource; public downloadprogressResponseBody (응답 body responsebody, downloadProgressListener ProgressListener) {this.ResponseBody = responsebody; this.progresslistener = ProgressListener; } @override public mediaType contentType () {return response.contentType (); } @override public long contentlength () {return response.contentLength (); } @override public bufferedSource source () {if (bufferedSource == null) {bufferedSource = okio.buffer (source (responsebody.source ())); } return bufferedSource; } 개인 소스 소스 (소스 소스) {return new ForwardingSource (소스) {Long TotalByTesRead = 0L; @override public long read (버퍼 싱크, long bytecount) ioexception {long bytesread = super.read (싱크, bytecount); // read () 읽기 수를 반환 하거나이 소스가 소진 된 경우 -1을 반환합니다. TotalByTesRead += ByTesRead! = -1? 바이트 레드 : 0; if (null! = progressListener) {progressListener.upDate (TotalByTesRead, response.contentLength (), bytesRead == -1); } return bytesread; }}; }} 공개 클래스 DownloadProgressInterceptor는 인터셉터 {private downloadProgressListener 리스너; public downloadprogressinterceptor (downloadProgressListener 리스너) {this.listener = 리스너; } @override public response intercept (체인 체인) IoException {응답 originalResponse = chain.proceed (chain.request ()); return originalResponse.newBuilder () .body (새로운 다운로드 progressResponseBody (OriginalResponse.body (), Listener) .build (); }}3. 다운로드 진행을위한 요소 클래스 만들기 :
공개 수업 다운로드는 {private int progress; 개인 장거리 FRILESIZE; 개인 긴 TotalFilesize; public int getProgress () {반환 진행; } 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 settotalfilesize (긴 TotalFilesize) {this.totalfilesize = TotalFilesize; } @override public int destremecontents () {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. 파일 네트워크 클래스 다운로드 :
public interface downloadservice {@streaming @get verietable <responsebody> 다운로드 (@url string url);}참고 : 여기 @url은 완전한 다운로드 URL입니다. 절편이 없습니다
public class downloadapi {private static final String tag = "downloadapi"; 비공개 정적 최종 int default_timeout = 15; 공공 개조 개조; public downloadapi (문자열 URL, 다운로드 progressListener 리스너) {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 문자열 URL, 최종 파일 파일, 가입자 구독자) {log.d (tag, "downloadApk :" + url); retrofit.create (downloadservice.class) .download (url) .subscribeon (schedulers.io ()) .unsubscribeon (schedulers.io ()). .ObServeon (schedulers.computation ()) .doonNext (new Action1 <inputStream> () {@override public void call (inputStream inputStream) {try {fileUtils.writeFile (inputStream, file);} catch (ioException e) {e.printStackex (); }}) .ObserveOn (AndroidSchedulers.MainThread ()) .SubScribe (가입자); }} 그런 다음이를 호출합니다.
네트워크는 서비스에서 수행됩니다
public class downloadservice 확장 intentservice {private static final string tag = "downloadservice"; Private NotificationCompat.Builder NotificationBuilder; Private NotificationManager NotificationManager; 개인 문자열 apkurl = "http://download.fir.im/v2/app/install/595c5959959d6901ca0004ac?download_token=1a9dfa8f248b6e45ea46bc5ed96a0a9e&source=update"; public downloadservice () {super ( "downloadservice"); } @override protected void on Handleintent (의도 의도) {notificationManager = (notificationManager) getSystemService (context.Notification_Service); NotificationBuilder = new NotificationCompat.Builder (this) .SetSmallicon (r.mipmap.ic_download) .setContentTitle ( "Download") .setContEntText ( "파일 다운로드") .setAutoCancel (true); NotificationManager.notify (0, notificationBuilder.build ()); 다운로드 (); } private void download () {downloadProgressListener Listener = new DownloadProgressListener () {@override public void update (long bytesread, long contentlength, boolean done) {download = new download (); download.settotalfilesize (contentlength); download.setCurrentFilesize (bytesread); int progress = (int) ((bytesread * 100) / contentlength); download.setprogress (진행); SendNotification (다운로드); }}; 파일 outputfile = 새 파일 (환경 .getexternalstoragepublicdirectory (환경 .directory_downloads), "file.apk"); 문자열 baseurl = stringUtils.gethostName (apkurl); 새 downlapi (baseurl, listener) .downloadapk (apkurl, outputfile, new subscriber () {@override public void void void oncompleted () {downloadCompleted ();} public void onerror (trownable e) {e.printstacktrace (); downloadCompleted (); oneer (tag, "oneRror. e.getMessage ()) @override public void onnext (object o) {}}); } private void download completed () {download = 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 (다운로드); NotificationBuilder.setProgress (100, download.getProgress (), false); NotificationBuilder.setContentText (StringUtils.getDatasize (다운로드 .getCurrentFilesize ()) + "/" + stringUtils.getDatasize (다운로드 .getToTalfilesize ())); NotificationManager.notify (0, notificationBuilder.build ()); } private void sendIntent (다운로드 다운로드) {의도 의도 = 새로운 의도 (mainActivity.message_progress); intent.putextra ( "다운로드", 다운로드); LocalBroadcastManager.getInstance (downloadService.this) .sendBroadcast (의도); } @override public void ontaskRemoved (의도 루트 인턴트) {notificationManager.cancel (0); }}MainActivity 코드 :
Public Class Mainactivity는 AppCompatactivity {public static final String message_progress = "message_progress"를 확장합니다. Private AppCompatButton BTN_Download; 개인 진행 상황 진행; Private TextView Progress_Text; Private Broadcastreceiver Broadcastreceiver = New Broadcastreceiver () {@override public void onreceive (컨텍스트 컨텍스트, 의도 의도) {if (intent.getaction (). equals (message_progress)) {다운로드 다운로드 = intent.getparcelableExtra ( "download"); progress.setprogress (download.getProgress ()); if (download.getProgress () == 100) {progress_text.settext ( "파일 다운로드 완료"); } else {progress_text.settext (stringUtils.getDatasize (download.getCurrentFilesize ()) + "/" + stringUtils.getDatasize (download.getTotalfilesize ())); }}}}}}}}; @override protected void onecreate (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) {의도 의도 = new 의도 (Mainactivity.this, downloadService.class); startErvice (의도);}); } private void registerReceiver () {localBroadcastManager bmanager = localBroadcastManager.getInstance (this); intentFilter intentFilter = new intentFilter (); intentfilter.addaction (message_progress); bmanager.registerReceiver (Broadcastreceiver, intentfilter); }}이 기사의 소스 코드 : Rxjava 구현 다운로드 파일을 개조합니다.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.