Cet article partage le code spécifique de RXJAVA Implémentation RXJAVA Fichier de téléchargement pour votre référence. Le contenu spécifique est le suivant
Cet article utilise: Retrofit + Rxjava
1. introduit:
// Rxjava Compile 'io.Reactivex: rxjava: Dermter.release' compile 'io.reactivex: rxandroid: lestor.release' // réseau - Squareup compile 'com.squareup.retrofit2: rétrofit: Retrofit. 'com.squareup.retrofit2: adaptateur-rxjava: dernier.release' compiler 'com.squareup.okhttp3: okhttp: letest.release' compile 'com.squareup.okhttp3: logging-interceptor: lestrelease' compile 'co.squareup.okhTtp3: Logging-interceptor.
2. Augmenter le téléchargement de la surveillance des progrès:
Interface publique DownloadProgressListener {void Update (long bytesRead, Long ContentLength, Boolean Done);} classe publique DownloadProgressResponseBody étend ResponseBody {Private ResponseBody ResponseBody; Private DownloadProgressListener ProgressListener; BufferedSource privé BufferedSource; Public DownloadProgressResponseBody (ResponseBody ResponseBody, DownloadProgressListener ProgressListener) {this.ResponseBody = ResponseBody; this.progressListener = ProgressListener; } @Override public MediaType ContentType () {return réponsebody.contentType (); } @Override public long contentLength () {return réponsebody.contentLength (); } @Override public BufferedSource Source () {if (BufferedSource == NULL) {BufferedSource = okio.buffer (source (ResponseBody.Source ())); } RETOUR BufferedSource; } Source privée Source (source Source) {return new Forwardingource (source) {long totalBytesRead = 0l; @Override public Long Read (tampon tampon, long byteCount) lève ioException {long bytesRead = super.read (swel, byteCount); // read () Renvoie le nombre d'octets lecture, ou -1 si cette source est épuisée. TotalBytesRead + = bytesRead! = -1? BytesRead: 0; if (null! = ProgressListener) {ProgressListener.update (TotalBytesRead, ResponseBody.ContentLength (), bytesRead == -1); } return bytesRead; }}; }} classe publique DownloadProgressInterceptor implémente Interceptor {Private DownloadProgressListener Écouteur; Public DownloadProGressInterceptor (téléchargement en auditeur deListener) {this.Listener = écouteur; } @Override La réponse publique Intercept (chaîne de chaîne) lève ioException {réponse originalResponse = chain.proceed (chain.request ()); return originalResponse.newBuilder () .Body (new DownloadProgressResponseBody (originalResponse.body (), écouteur)) .build (); }}3. Créer une classe d'éléments pour le téléchargement Progress:
Le téléchargement de classe publique implémente Parcelable {private int progress; Private Long Currentfilesize; Totalfile long privé; 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 SettotalFileSize (long totalfilesize) {this.totalfilesize = totalFileSize; } @Override public int décontant () {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 CreateFrombcel (Parcel Source) {return new Download (source); } @Override Public Download [] newArray (int size) {return new Download [size]; }};}4. Téléchargez la classe du réseau de fichiers:
Interface publique Téléchargement de téléchargement {@Streaming @get observable <Sponsebody> download (@Url String URL);}Remarque: Ici @url est une URL de téléchargement complète; pas d'interception
classe publique DownloadAPI {private static final string tag = "downloadapi"; private static final int default_timeout = 15; Modification du public Rétrofice; Public DownloadAPI (URL de chaîne, téléchargement de l'écouteur de Listener) {téléchargementProgressInterceptor interceptor = new DownloadProgressInterceptor (écouteur); Okhttpclient client = new okhttpclient.builder () .addinterceptor (interceptor) .retryConnectionFailure (true) .connectTimeout (default_timeout, timeunit.seconds) .build (); Retrofit = new RESTOFIT.BUILDER () .BASEURL (URL) .Client (client) .AddCalladapterFactory (rxjavacalladapterFactory.create ()) .build (); } public void downloadaPK (@Nonnull String URL, fichier final File, abonné abonné) {log.d (tag, "téléchargement:" + url); ringofit.create (downloadService.class) .Download (URL) .SubScribeon (schedulers.io ()) .unSubScribeon (schedulers.io ()) .map (new func1 <réponsebody, inputStream. .ObServeOn (Schedulers.Compputation ()) .DoonNext (new Action1 <putStream> () {@Override public void Call (InputStream InputStream) {try {FileUtils.WriteFile (InputStream, File);} Catch (ioException e) {e.PrintStackTrace (); Throw CustomAisexception (E.getMessage (), e); .ObServeon (AndRoidschedulers.Mainthread ()) .Subscribe (abonné); }} Ensuite, ça s'appelle:
Le réseau est effectué dans le service
Classe publique Téléchargement de téléchargement étend IntenService {private static final string tag = "downloadService"; NotificationCompat.Builder NotificationBuilder; NotificationManager NotificationManager; chaîne privée apkurl = "http://download.fir.im/v2/app/install/595c5959959d6901ca0004ac?download_token=1a9dfa8f248b6e45ea46bc5ed96a0a9e&source=update"; public downloadService () {super ("downloadService"); } @Override Protected void onHandleIntent (INTING INTING) {notificationManager = (notificationManager) GetSystemService (context.notification_service); notificationBuilder = new notificationcompat.builder (this) .setsmallicon (r.mipmap.ic_download) .setContentTitle ("download") .setContentText ("Downloading Fichier") .SetAutoCancel (true); notificationManager.Notify (0, notificationBuilder.build ()); télécharger(); } private void download () {downloadProgressListener écouteur = new téléchargementProgressListener () {@Override public void update (long bytesread, long contentLength, booléan fait) {télécharger télécharger = new download (); téléchargement.setTotalFileSize (ContentLength); téléchargement.setCurrentFileSize (bytesRead); int progress = (int) ((byTesRead * 100) / contentLength); téléchargement.setProgress (progrès); SendNotification (téléchargement); }}; File OutputFile = nouveau fichier (Environment.getExternalStoragePublicDirectory (Environment.Directory_Downloads), "file.apk"); String burnalUrl = StringUtils.GethostName (apkurl); New DownloadAPI (BustainUl, auditeur) .DownloadApk (apkurl, outputFile, new abonné () {@Override public void oncompleted () {downloadCompleted ();} @Override public void onError (Throwable E) {e.printStackTrace (); téléchargement (); } @Override public void onNext (objet o) {}}); } private void downloadCleted () {download download = new Download (); téléchargement.setProgress (100); SendIntent (téléchargement); notificationManager.Cancel (0); notificationBuilder.setProgress (0, 0, false); notificationBuilder.setContentText ("Fichier téléchargé"); notificationManager.Notify (0, notificationBuilder.build ()); } private void Sendnotification (télécharger télécharger) {sendIntent (download); notificationBuilder.setProgress (100, téléchargement.getProgress (), false); notificationBuilder.setContentText (stringUtils.getDatasize (téléchargement.getCurrentFilesize ()) + "/" + stringUtils.getDatasize (téléchargement.getTotalFileSize ())); notificationManager.Notify (0, notificationBuilder.build ()); } private void SendIntent (téléchargement de téléchargement) {Intent Intent = new Intent (mainActivity.Message_Progress); intention.putextra ("Download", Download); LocalbroadcastManager.getInstance (téléchargement de téléchargement. } @Override public void ontaskReMoved (Intent RoatIntent) {notificationManager.Cancel (0); }}Code de mainactivité:
La classe publique MainActivity étend AppCompatActivity {public static final String Message_Progress = "Message_Progress"; AppRompCatButton privé BTN_DOWNLOAD; Progress Progress Progrès; TextView privé Progress_text; privé BroadCastReceiver BroadCastReceiver = new BroadCastReceiver () {@Override public void onReceive (contexte de contexte, intention intention) {if (intent.getAction (). Equals (Message_Progress)) {téléchargement téléchargé = INTER.GETPARCELableExtra ("Download"); Progress.SetProgress (téléchargement.getProgress ()); if (download.getProgress () == 100) {Progress_text.setText ("File Download complet"); } else {progress_text.setText (stringUtils.getDatasize (téléchargement.getCurrentFilesize ()) + "/" + stringUtils.getDatasize (téléchargement.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); registreReceiver (); btn_download.setOnClickListener (new View.OnClickListener () {@Override public void onClick (View View) {INTERNET INTENT = NOUVEAU INTENT (MainActivity.This, téléchargement pourvoi } private void registerReceiver () {localBroadcastManager bmanager = localBroadcastManager.getInstance (this); IntentFilter IntentFilter = new IntentFilter (); IntentFilter.Addaction (message_progress); Bmanager.RegisterReceiver (BroadCastReceiver, IntentFilter); }}Code source de cet article: Retrofit Rxjava Implémentation Implémentation Fichier de téléchargement
Ce qui précède est tout le contenu de cet article. J'espère que cela sera utile à l'apprentissage de tous et j'espère que tout le monde soutiendra davantage Wulin.com.