Dieser Artikel teilt den spezifischen Code der Rxjava -Implementierungsdownload -Datei für Ihre Referenz. Der spezifische Inhalt ist wie folgt
Dieser Artikel verwendet: Nachrüst + rxjava
1. eingeführte:
// rxjava compile 'io.reactivex: rxjava: neuest.release' compile 'io.reactivex: rxandroid: neuest.release' // network - squareUp compile 'com.squareUp.retrofit2: retrofit: neueste. 'com.SquareUp.Retrofit2: adapter-rxjava: lunster.release' com.squareup.okhttp3: Okhttp: neuest.Release 'Compile' com.squareUp.okhttp3: Logging-Interceptor: neueste 'com.ch. com.squareUp.
2. erhöhen Sie den Download -Fortschrittsüberwachung:
öffentliche Schnittstelle DownloadProgressListener {void Update (Long BytesRead, Long ContentLength, Boolean Done);} öffentliche Klasse DownloadProgressResponseBody erweitert ResponseBody {private responseBody responseBody; private DownloadProgressListener ProgressListener; private bufferedSource bufferedSource; public downloadProgressResponseBody (Antwortbody ResponseBody, DownloadProgressListener ProgressListener) {this.ResponseBody = Antwortbodus; this.progressListener = progresorListener; } @Override public mediType contentType () {return responseBody.contentType (); } @Override public long contentLength () {return responseBody.contentLength (); } @Override public bufferedSource Source () {if (bufferedSource == null) {bufferedSource = oKIO.Buffer (Quelle (ResponseBody.Source ())); } return bufferedSource; } private Quelle Source (Quelle Quelle) {neuer Weiterleitung (Quelle) {Long TotalByTesRead = 0L; @Override public Long Read (Buffer Sink, Long byteCount) löst ioException {long byteRead = super.read (Sink, ByteCount) aus; // read () gibt die Anzahl der Lesebytes zurück oder -1, wenn diese Quelle erschöpft ist. TotalByTesRead += ByteSread! = -1? BytesRead: 0; if (null! } return bytesread; }}; }} öffentliche Klasse DownloadProgressInterceptor implementiert Interceptor {private DownloadProgressListener -Listener; public downloadProgressInterceptor (DownloadProgressListener -Listener) {this.Listener = Listener; } @Override public response intercept (Chain Chain) löst ioException {response originalResponse = chain.procece (chain.Request ()); return originalResponse.newbuilder () .body (neue DownloadProgressResponseBody (OriginalResponse.body (), Hörer) .build (); }}3. Erstellen Sie die Elementklasse zum Download -Fortschritt:
öffentliche Klasse Download implementiert paketable {private int progress; privat langer Stromfilmisze; privat langes Total -filesize; public int getSProgress () {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 settotAnfileSize (long TotalFileSize) {this.totalFileSize = TotalFileSize; } @Override public int cremecteContents () {return 0; } @Override public void writeToparcel (Parcel dest, int flags) {dest.writeInt (this.progress); Dest.WriteLong (this.currentFileSize); Dest.WriteLong (this.totalFileSize); } public download () {} geschützter Download (Parcel in) {this.progress = in.readint (); this.currentFileSize = in.readlong (); this.totalFileSize = in.readlong (); } public static endgültiger parzelable } @Override public download [] newArray (int size) {Neuen Download zurückgeben [Größe]; }};}4. Laden Sie die Datei -Netzwerkklasse herunter:
public interface downloadService {@streaming @get Observable <AnsseeBody> download (@url String url);}Hinweis: Hier ist @url eine vollständige Download -URL; Kein Abfangen
public class downloadapi {private static final string tag = "downloadapi"; private statische endgültige int default_timeout = 15; öffentliche Nachrüstung nachrüst; public downloadApi (String -URL, DownloadProgressListener -Listener) {DownloadProgressInterceptor Interceptor = new DownloadProgressInterceptor (Listener); 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, endgültige Dateidatei, Abonnenten -Abonnent) {log.d (Tag, "Downloadapk:" + url); retrofit.create (downloadService.class) .download (URL) .Subscribeon (planlers.io ()) .UnSubScribeon (Schedulers.io () .MAP (neuer func1 <responseBody, InputStream> () {@Override öffentliche InputStream (Reaktionsbody) {zurücksagen) {zurücksagen. .OBSERVEON (SCHLADULERS.COMPUTATION () .DOONNEXT (NEU ACTION1 <NINGTSTREAM> () {@Override public void call (InputStream InputStream) {try {FileUtils.WritFile (InputStream); .OBSERVEON (Androidschedulers.mainThread ()) .Subscribe (Abonnent); }} Dann heißt es:
Das Netzwerk erfolgt im Dienst
öffentliche Klasse DownloadService erweitert IntentService {private statische endgültige String -Tag = "DownloadService"; private NotificationCompat.Builder NotificationBuilder; private NotificationManager NotificationManager; private String apkurl = "http://download.fir.im/v2/app/install/595c5959959d6901ca0004ac?download_Token=1A9DFA8F248B6E45EA4BC5ED96A0A9E&SSAUSE=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 ("Downloading -Datei") .setAutocancel (true); NotificationManager.Notify (0, NotificationBuilder.build ()); herunterladen(); } private void download () {DownloadProgressListener Listener = new DownloadProgressListener () {@Override public void update (Long ByteSread, Long ContentLength, Boolean Done) {Download Download = new download (); Download.SettotAllePileSize (ContentLength); Download.SetCurrentFileSize (ByteSread); int progress = (int) ((byteSread * 100) / contentLength); Download.SetProgress (Fortschritt); SendNotification (Download); }}; Datei outputFile = neue Datei (Umgebung.GetexternalStoragePublicDirectory (Umgebung.Directory_downloads), "Datei.APK"); String baseUrl = Stringutils.gethostname (apkurl); New DownloadAPI (Basisurl, Hörer) .Downloadapk (apkurl, outputFile, neuer subscriber () {@Override public void onCompleted () {downloadCompleted ();} @Override public void onerror (Throwable E) {E. printacktrace (); } @Override public void Onnext (Objekt o) {}}); } private void downloadCompleted () {download = new download (); Download.SetProgress (100); SendIntent (Download); NotificationManager.Cancel (0); notificationBuilder.setProgress (0, 0, false); NotificationBuilder.SetContentText ("Datei heruntergeladen"); NotificationManager.Notify (0, NotificationBuilder.build ()); } private void sendNotification (Download Download) {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 (download) {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); }}Mainaktivitätscode:
MainActivity der öffentlichen Klasse erweitert die AppCompataktivität {public static Final String message_progress = "message_progress"; private AppCompatbutton btn_download; private Progress -BAR -Fortschritte; private textView progress_text; private radcastreceiver sroadcastreceiver = new Broadcastreceiver () {@Override public void onReceive (Kontextkontext, Intent Intent) {if (intent.getAction (). Equals (Message_Progress)) {Download = intent.getParcelableExtra ("Download"); progress.setProgress (download.getProgress ()); if (download.getProgress () == 100) {progress_text.setText ("Datei herunterladen"); } else {progress_text.setText (stringutils.getDataSize (download.getCurrentFileSize ()) + "/" + Stringutils.getDataSize (download.gettotAlFileSize ())); }}}}}}}; @Override Protected void OnCreate (Bündel 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 (neue Ansicht. } private void RegisterReceiver () {localBroadcastManager bmanager = localBroadcastManager.getInstance (this); IntentFilter IntentFilter = new IntentFilter (); IntentFilter.AddAction (Message_Progress); bmanager.registerReceiver (sendergreifer, IntentFilter); }}Quellcode dieses Artikels: Rxjava -Implementierungsdownload -Datei nachrüsten
Das obige ist der gesamte Inhalt dieses Artikels. Ich hoffe, es wird für das Lernen aller hilfreich sein und ich hoffe, jeder wird Wulin.com mehr unterstützen.