Este artigo compartilha o código específico do Código de Retrofit RXJAVA Download Arquivo de Download para sua referência. O conteúdo específico é o seguinte
Este artigo usa: retrofit + rxjava
1.Introduzido:
// rxjava compile 'io.reactivex: rxjava: mais recente.Release' compile 'io.reactivex: rxandroid: mais recente.Release' // Network - SquareEase Compile 'com.squareUp.Trofit2: Retrofit: mais recente.ReLeEase' Compile 'com.square. 'com.squareup.retrofit2: adaptador-rxjava: mais recente.release' compile 'com.squareup.okhttp3: okhttp: mais recente.release' compile 'com.squareUp.Okhtp3: Loging-interceptor: mais recente.Release' Compile 'com.sTearep.sQueStar.Okhtp3: Loging-Interceptor: mais recente.Release' Compile 'com.sTeare.sTeare.Okhtp3
2. Aumente o Monitoramento de Progresso do Download do Download:
Public Interface DownloadProgressListener {Void Update (Long Bytesread, Long ContentLength, Boolean Done);} classe pública DownloadProgressResponseBody estende a resposta {private ResponseBodybodybody; Download PrivateProgressListener ProgressListener; Private buffersource buffersource; public DownloadProgressResponseBody (resposta de resposta, downloadprogressListener ProgressListener) {this.ResponseBody = ResponseBody; this.ProgressListener = ProgressListener; } @Override public MediaType contentType () {return ResponseBody.ContentType (); } @Override public Long contentLength () {return ResponseBody.ContentLength (); } @Override public bufferSource Source () {if (buffersource == null) {buffersource = okio.buffer (origem (respostabody.source ())); } retornar buffersource; } fonte privada fonte (fonte de origem) {return New ForwardingSource (origem) {Long TotalBytesRead = 0l; @Override Public Long Read (Buffer Sink, Long ByteCount) lança IoException {Long bytesread = super.read (Sink, ByteCount); // read () Retorna o número de bytes leitura, ou -1 se essa fonte estiver esgotada. TotalBytesRead += bytesRead! = -1? bytesread: 0; if (null! = ProgressListener) {ProgressListener.UpDate (totalbytesread, ResponseBody.ContentLength (), bytesRead == -1); } retornar bytesread; }}; }} classe pública DownloadProgressIntercept implementa Interceptor {Private DownloadProgressListener ouvinte; public DownloadProgressIntercept (DownloadProgressListener ouvinte) {this.Listener = ouvinte; } @Override Resposta pública Intercept (cadeia) lança IoException {Response OriginalResponse = Chain.proeced (Chain.Request ()); Retornar OriginalResponse.NewBuilder () .Body (New DownloadProgressResponseBody (OriginalResponse.body (), ouvinte)) .build (); }}3. Crie classe de elemento para o progresso do download:
classe pública Download implementa o Parcelable {private int Progress; Private Long CurrentFilesize; Totalfiles Totalfiles longo privado; public int getProgress () {retornar progresso; } public void setProgress (int Progress) {this.Progress = Progress; } public long getCurrentFilesize () {return currentFilesize; } public void setCurrentFilesize (long curtFilesize) {this.currentfilesize = currentFilesize; } public Long getTotalFilESIZE () {return totalfilesize; } public void SettotalFilesize (Long Totalfilesize) {this.toTalFilIleSize = totalfilesize; } @Override public int descriContents () {return 0; } @Override public void WRITETOPARCEL (PARCEL DEST, INT FLANGS) {DEST.WRITEINT (this.Progress); Dest.Writelong (this.CurrentFilesize); Dest.Writelong (this.totalfilesize); } public Download () {} Download Protected (Parcel in) {this.Progress = in.readInt (); this.currentFilesize = in.readlong (); this.TotalFilIleSize = in.readlong (); } public static final Parcelable.Creator <Orling> Creator = new Parcelable.Creator <Orling> () {@Override public Download CreateFromParcel (Parcel Source) {return New Download (fonte); } @Override public Download [] newArray (int size) {return New Download [size]; }};}4. Baixe a classe de rede de arquivos:
Public Interface DownloadService {@streaming @get observable <Responsebody> Download (@url string url);}Nota: Aqui @url é um URL completo de download; Sem interceptação
classe pública DownloadApi {private static final string tag = "DownloadApi"; private estático final int default_timeout = 15; retrofit público de retrofit; public DownloadApi (String URL, DownloadProgressListener ouvinte) {DownloadProgressInterceptor Interceptor = new DownloadProgressIntercept (ouvinte); Okhttpclient client = new okhttpclient.builder () .addinterceptor (interceptor) .retryonconnectionFailure (true) .connectTimeout (default_timeout, timeunit.seconds) .build (); retrofit = new ROTROFIT.Builder () .baseurl (url) .client (client) .addcalladapterfactory (rxjavacalladapterfactory.create ()) .build (); } public void DownloadApk (@Nonnull String URL, arquivo final do arquivo, assinante assinante) {log.d (tag, "DownloadApk:" + url); retrofit.create (downloadservice.class) .Download (url) .subScribeon (schedulers.io ()) .UnsubScribe (schedulers.io ()) .map (new func1 <s ResponseMbody, retorntream> () {@Override public IngStry Call (resposta corpodybody) { .OBSERVEON (schedulers.computation ()) .doonNext (new Action1 <inputStream> () {@Override public void Call (inputStream inputStream) {try {fileUtils.WRITEFILE (inputStream, file);} catch (ioException E) {e.PrintStackTrace (); }) .OBSERVEON (Androidschedulers.Mainthread ()) .SubScribe (assinante); }} Então é chamado:
A rede é feita no serviço
classe pública DownloadService estende o IntentService {private Static final String tag = "DownloadService"; private notificationcompat.builder notificationbuilder; Notificação PrivateManager NotificationManager; Private String apkurl = "http://download.fir.im/v2/app/install/595c5959959d6901ca0004ac?download_token=1a9dfa8f248b6e45ea46bc5ed96a0a9e.source=Source=SOURCE=SOURCE=SOURCE=SOURCE "DEDRECHEDRECHEDRECHEDRECHEDRECHEDRECHEDRECHEDC5ED96A1A1A1A1A1A. public DownloadService () {Super ("DownloadService"); } @Override Protected void onHandleIntent (intenção intenção) {notificationManager = (NotificationManager) getSystemService (context.notification_service); notificationbuilder = new notificationcompat.builder (this) .SetsMallicon (r.mipmap.ic_download) .setContentTitle ("Download") .SetContentText ("Filenciamento de arquivo") .SetAutocancel (true); notificationManager.Notify (0, notificationBuilder.Build ()); download(); } private void Download () {DownloadProgressListener ouvinte = 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 (Progress); sendNotification (download); }}; Arquivo outputFile = new File (Environment.GetexternalStoragePublicDirectory (Environment.Directory_Downloads), "file.apk"); String baseurl = stringUtils.gethostName (apkurl); novo downloadapi (baseurl, ouvinte) .DownloadApk (apkurl, outputFile, new Subscrier () {@Override public void oCompleted () {downloadcompleted ();} @Override void onError (throwable e) {E.PrintStackTrace (); } @Override public void onNext (objeto o) {}}); } private void DownloadCompleted () {Download download = new Download (); download.setProgress (100); sendintent (download); notificationManager.cancel (0); notificationbuilder.setProgress (0, 0, false); notificationBuilder.SetContentText ("FILE baixado"); notificationManager.Notify (0, notificationBuilder.Build ()); } private void sendNotification (download do 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 do download) {intenção intenção = new Intent (mainActivity.Message_Progress); intent.putextra ("download", download); LocalBroadcastManager.getInstance (DownloadService.This) .Sendbroadcast (intenção); } @Override public void ontaskremoved (intenção rootIntent) {notificationManager.cancel (0); }}Código MainActivity:
classe pública MainActivity estende AppCompatactivity {public static final string message_progress = "message_Progress"; AppCompatbutton privado BTN_DOWNLOAD; Progresso privado da barra de progresso; Private TextView Progress_Text; Private BroadCastreCeiver BroadCastreCeiver = new BroadCastreCeiver () {@Override public void onReceive (contexto de contexto, intenção intenção) {se (intent.getAction (). Equals (Message_Progress)) {Download = Intent.GetPeRexableExtra ("Download"); Progress.setProgress (download.getProgress ()); if (download.getProgress () == 100) {progress_text.settext ("Download do arquivo complete"); } else {progress_text.settext (stringUtils.getDataSize (Download.getCurrentFilesize ()) + "/" + stringUtils.getDataSize (Download.gettotalFileSize ())); }}}}}}}; @Override Protected void onCreate (pacote savedInstancestate) {super.oCreate (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.This, DownloadService.Class); StartService (intenção);}}); } private void RegisterReceiver () {localbroadcastManager bmanager = localBroadcastManager.getInstance (this); IntentFilter intentFilter = new IntentFilter (); IntentFilter.addaction (Message_Progress); Bmanager.RegisterReceiver (BroadCastreceiver, IntentFilter); }}Código fonte deste artigo: ROTROFIT RXJAVA IMPLEMPENSABILIDADE FILHO
O exposto acima é todo o conteúdo deste artigo. Espero que seja útil para o aprendizado de todos e espero que todos apoiem mais o wulin.com.