Artikel ini membagikan kode spesifik file unduhan implementasi RXJAVA untuk referensi Anda. Konten spesifiknya adalah sebagai berikut
Artikel ini menggunakan: retrofit + rxjava
1.Tentroduced:
// rxjava kompilasi 'io.reactivex: rxjava: terbaru.release' compile 'io.reactivex: rxandroid: terbaru com.squareup.retrofit2: adaptor-rxjava: terbaru
2. Tingkatkan Pemantauan Kemajuan Unduh:
Antarmuka publik DownloadprogressListener {void update (long bytesread, long contentLength, boolean selesai);} Public Class DownloadProgressResponseBody memperluas responsbody {private responsebody responseBody; Private DownloadProgressListener ProgressListener; Sumber Buffered Private Source; Public DownloadProgressResponseBody (ResponseBody ResponseBody, DownloadProgressListener ProgressListener) {this.responseBody = ResponseBody; this.progressListener = ProgressListener; } @Override public mediatype contentType () {return responseBody.contentType (); } @Override public long contentLength () {return responseBody.contentLength (); } @Override Public BufferedSource Source () {if (bufferedSource == null) {bufferedSource = okio.buffer (sumber (responseBody.source ())); } return bufferedSource; } sumber private source (sumber sumber) {return new forwardingsource (sumber) {long totalBytesRead = 0l; @Override public long read (buffer wastafel, long bytecount) melempar ioException {long bytesread = super.read (wastafel, bytecount); // baca () Mengembalikan jumlah byte yang dibaca, atau -1 jika sumber ini habis. TotalByTesRead += Bytesread! = -1? Bytesread: 0; if (null! = progressListener) {progressListener.update (TotalBytesRead, responseBody.ContentLength (), bytesread == -1); } return bytesread; }}; }} Kelas Publik DownloadProgressInterceptor mengimplementasikan Interceptor {Private DownloadProgressListener Listener; Public DownloadProgressInterceptor (DownloadProgressListener Listener) {this.listener = pendengar; } @Override Public Response Intercept (rantai rantai) melempar ioException {response originalResponse = chain.prroce (chain.Request ()); return originalResponse.newBuilder () .body (New DownloadProgressResponseBody (originalResponse.body (), pendengar)) .build (); }}3. Buat kelas elemen untuk kemajuan unduhan:
unduhan kelas publik mengimplementasikan parcelable {private int progress; Private Long CurrentfileSze; Totalfile panjang pribadi; publik int getProgress () {pengembalian kemajuan; } 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 (long totalFileSize) {this.totalfileSize = TotalFileSize; } @Override public int gambaran () {return 0; } @Override public void writeToParcel (parcel dest, int flags) {dest.writeint (this.progress); dest.writelong (this.currentfileSize); dest.writelong (this.totalfileSize); } download publik () {} Download Protected (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 Unduh publik createFromparcel (sumber parcel) {return baru unduhan (sumber); } @Override public download [] newArray (ukuran int) {return new download [size]; }};}4. Unduh kelas jaringan file:
Download Interface Publik {@streaming @get Observable <Respessbody> Unduh (@Url string url);}Catatan: di sini @Url adalah URL unduhan lengkap; tidak ada intersep
download kelas publik {private static final string tag = "downloadapi"; private static final int default_timeout = 15; retrofit retrofit publik; downloadapi publik (string url, downloadprogresslistener listener) {downloadprogressInterceptor interceptor = new downloadprogressInterceptor (pendengar); OKHTTPCLIENT CLIENT = OKHTTPCLIENT.BUILDER () baru. retrofit = retrofit.builder baru () .baseUrl (url) .client (klien) .addcallAdapterfactory (rxjavacallapterfactory.create ()) .build (); } public void downloadapk (@nonnull string url, file file akhir, pelanggan pelanggan) {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(ResponseBody responseBody) { return responseBody.byteStream(); } }) .observeon (schedulers.computation ()) .doonNext (Action new Action1 <InputStream> () {@Override public void call (inputStream inputStream) {try {fileutils.writeFile (inputStream, file);} catch (ioException e) {e.printrace (inputstream, file);} catch (ioException e) {e.printrace (inputRace, file);} catch (ioException e) {e.printrace (inputStrace); }}}) .observeon (androidschedulers.mainthread ()) .subscribe (pelanggan); }} Kemudian disebut:
Jaringan dilakukan dalam layanan
Public Class DownloadService Extends IntentService {private static final string tag = "downloadservice"; pemberitahuan pribadiCompat.Builder NotificationBuilder; pemberitahuan pemberitahuan privat NotificationManager; private string apkurl = "http://download.fir.im/v2/app/install/595c595959d6901ca0004ac?download_token=1A9DFA8F248B6E45A46BC5ED96A0A9E&SOURCE=UPDE=UPDE=UPDEORCE=UPDEORCE=UPDEORCE=UPDEORCE=UPDICE=UPD96A 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 ("unduh") .setContentText ("Unduh File") .setAutocancel (true); notificationManager.notify (0, notificationBuilder.build ()); unduh (); } private void download () {downloadProgressListener listener = new downloadProgressListener () {@Override public void update (long bytesread, long contentLength, boolean selesai) {download download = new download (); download.settotalfilesize (ContentLength); download.setCurrentFileSize (bytesread); int progress = (int) ((bytesread * 100) / contentLength); download.setprogress (progress); sendNotification (unduh); }}; File outputFile = file baru (lingkungan.getExternalStoragePublicDirectory (lingkungan.directory_downloads), "file.apk"); String baseUrl = stringutils.gethostname (apkurl); New DownloadAPI (BaseUrl, pendengar) .DownloadAPK (apkurl, outputFile, pelanggan baru () {@Override public void onCompleted () {downloadcompleted ();} @Override public void onError (throwable e) {e.printstack (); download public ("lOMRINREOR (: lOVRINTECT (); e.getMessage ());} @Override public void onNext (objek o) {}}); } private void downloadCompleted () {download download = download baru (); download.setprogress (100); SendIntent (unduh); notificationManager.cancel (0); notificationBuilder.setprogress (0, 0, false); notificationBuilder.setContentText ("File diunduh"); notificationManager.notify (0, notificationBuilder.build ()); } private void sendNotification (unduh unduh) {sendIntent (unduh); notificationBuilder.setProgress (100, download.getProgress (), false); notificationBuilder.setContentText (stringutils.getDataSize (download.getCurrentFileSize ()) + "/" + stringutils.getDataSize (download.gettotalfilesize ())); notificationManager.notify (0, notificationBuilder.build ()); } private void sendIntent (unduh unduh) {Intent Intent = new Intent (MainActivity.Message_progress); intent.putextra ("unduh", unduh); LocalbroadcastManager.getInstance (downloadservice.ini) .sendBroadcast (intent); } @Override public void ontaskremoved (intent rootIntent) {notificationManager.cancel (0); }}Kode MainActivity:
MainActivity kelas publik memperluas appCompatactivity {public static final string message_progress = "message_progress"; Private AppCompatButton btn_download; Kemajuan Progresbar Pribadi; Private TextView Progress_text; Private BroadCastreceiver BroadCastreceiver = new BroadCastreceiver () {@Override public void onreceive (konteks konteks, niat intent) {if (intent.getAction (). Equals (message_progress)) {download download = intent.getParcelablextra ("unduh"); progress.setProgress (download.getProgress ()); if (download.getProgress () == 100) {progress_text.setText ("File download 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 (view.onClickListener baru () {@Override public void onClick (view view) {intent intent = new Intent (MainActivity.ini, unduhan, class); startService (intent);}}); } private void registerReceiver () {localbroadcastManager bmanager = localbroadcastManager.getInstance (this); Intentfilter intentfilter = intentfilter baru (); intentfilter.addaction (message_progress); bmanager.registerreceiver (Broadcastreceiver, IntentFilter); }}Kode sumber artikel ini: Retrofit RXJAVA File Unduh Implementasi
Di atas adalah semua konten artikel ini. Saya berharap ini akan membantu untuk pembelajaran semua orang dan saya harap semua orang akan lebih mendukung wulin.com.