В этой статье используется конкретный код модернизации файла загрузки RXJAVA для вашей ссылки. Конкретный контент заключается в следующем
В этой статье используется: Модернизация + rxjava
1. интродуцирован:
// rxjava compile 'io.reactivex: rxjava: andal.release' compile 'io.reactivex: rxandroid: ald.release' // network - squareup compile 'com.squareup.retrofit2: retrofit: afled.Release' compile 'com.square 'Com.squareup.retrofit2: Adapter-rxjava: astald.release' compile 'com.squareup.okhttp3: okhttp: astald.release' compile 'com.squareup.okhttp3: logging-interceptor: aldess.release' compile 'com.squareup.oktp3: vome-interceptor.
2. Увеличьте мониторинг прогресса загрузки:
Public Interface Download ProgressListener {void Update (Long BytesRead, Long ContentLength, Boolean выполнено);} public class downloadprogressresponsebody extends responsebody {private responsebody cody; Private DownloadProgressListener ProgressListener; Частный буферизатор BufferedSource; public DownloadProgressResponseBody (обратное тело ответа, загрузка ProgressListener 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 (source (responsebody.source ())); } return BufferedSource; / @Override public long Read (буферная раковина, длинный байтэлект) бросает ioexception {long bytesread = super.read (раковина, bytecount); // read () Возвращает количество чтения байтов или -1, если этот источник исчерпан. TotalBytesRead += BytesRead! = -1? байспич: 0; if (null! = ProgressListener) {ProgressListener.Update (totalBytesRead, responsebody.contentLength (), bytesRead == -1); } вернуть BytesRead; }}; }} Public Class DownloadProgressInterceptor реализует Interceptor {private DownloadProgressLister Sluster; public DownloadProgressInterceptor (DownloadProgressListener Slister) {this.Listener = слушатель; } @Override public response intercept (цепочка цепи) бросает ioException {response riginalresponse = chain.proceed (chain.request ()); return riginalResponse.newbuilder () .body (новый загрузка progressresponsebody (originalresponse.body (), слушатель)) .build (); }}3. Создайте класс элементов для скачивания прогресс:
Общедоступный класс Скачать реализует посылок {private int progress; частный Long -FileSize; частный длинный общий диапазон; public int getProgress () {вернуть прогресс; } public void setProgress (int progress) {this.progress = progress; } public long getCurrentFilesize () {return CurrentFilesize; } public void setCurrentFilesize (long -curyFilesize) {this.currentFilesize = currentFilesize; } public long getTotAlfilesize () {return totalFilesize; } public void centotalFilesize (long totalfilesize) {this.TotalFilesize = totalFilesize; } @Override public int descrizeContents () {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 <downly> creator = new parcelable.creator <downly> () {@override public скачать createfromparcel (parcel source) {return new Download (Source); } @Override public скачать [] newarray (int size) {return new Download [size]; }};}4. Загрузите класс File Network:
public interface DownloadService {@Streaming @Get Observable <sessoncebody> Загрузить (@URL String URL);}ПРИМЕЧАНИЕ. Здесь @URL - полный URL загрузки; Нет перехвата
Public Class DownloadApi {private Static Final String Tag = "DownloadApi"; Private Static Final int default_timeout = 15; модернизация общественного модернизации; public DownloadApi (String URL, DownloadProgressListener Sluster) {DownloadProgressInterceptor Interceptor = New DownloadProgressInterceptor (слушатель); Okhttpclient client = new okhttpclient.builder () .AdInterceptor (Interceptor) .retryonConnectionFailure (true) .connectTimeOut (default_timeout, timeUnit.seconds) .build (); MORFIT = новый MORFIT.BUILDER () .BASEURL (URL) .CLIVE (клиент) .ADDCALLADAPTERFACTORY (RXJAVACALLADAPTERFACTORY.CREATE ()) .BUILD (); } public void DownloadApk (@Nonnull String URL, окончательный файл файла, подписчик подписчика) {log.d (Tag, "DownloadApk:" + url); MORFIT.Create (DownloadService.class) .download (url) .subscribeon (schedulers.io ()) .unsubscribeon (shadulers.io ()) .map (новый func1 <responsebody, inputStream> () {@Override publicstream Call (ответный ответ Callody) {return responsebody); .observeon (shadulers.compatation ()) .doonnext (new action1 <pintstream> () {@override public void call (inputstream inputstream) {try {fileutils.writefile (inputstream, file);} catch (ioexception e) {e.printstacktrace (); throw new cumentizexception (e.) {e.printstacktrace ();); .observeon (androidschedulers.mainthread ()) .subscribe (подписчик); }} Тогда это называется:
Сеть сделана в сервисе
Public Class DownloadService Extends intentService {Private Static Final String Tag = "DownloadService"; Частное уведомление compat.builder уведомление о повеселе; частное уведомление Manager NotificationManager; Приватная строка apkurl = "http://download.fir.im/v2/app/install/595c5959959d6901ca0004ac?download_token=1a9dfa8f248b6e45a46bc5ed96a0a9e&source=update"; public downloadService () {super ("DownloadService"); } @Override Protected void onHandleIntent (намерение) {notificationManager = (natificationManager) getSystemService (context.notification_service); notificationBuilder = new NotificationCompat.Builder (this) .setSmallicon (r.mipmap.ic_download) .setContentTitle ("Загрузка") .SetContentText ("Загрузка файла") .setAutocancel (true); natificationManager.notify (0, nобонстрирование builder.build ()); скачать(); } private void Download () {DownloadProgressListener Sluster = New DownloadProgressListener () {@Override public void Update (Long BytesRead, Long ContentLength, Boolean Dod) {Скачать = new Download (); Загрузить.setTotalFilesize (ContentLength); Загрузить.setCurrentFilesize (BytesRead); int progress = (int) ((BytesRead * 100) / contentLength); Загрузка.setProgress (Progress); SendNotification (скачать); }}; File outputFile = новый файл (Environment.GetExternalStoragePublicDirectory (Environment.Directory_downloads), "file.apk"); String baseurl = stringutils.gethostname (apkurl); New DownloadApi (baseurl, слушатель) .downloadApk (apkurl, outputfile, new neccriber () {@Override public void oncompleted () {downloadCpleted ();} @Override public void onerror (throwable e) {e.printStacktrace ();); } @Override public void onNext (Object O) {}}); } private void downloadcompleted () {download download = new Download (); Загрузка.setProgress (100); SendIntent (скачать); уведомление manager.cancel (0); natificationbuilder.setProgress (0, 0, false); natificationBuilder.setContentText ("файл загружен"); natificationManager.notify (0, nобонстрирование builder.build ()); } private void SendNotification (скачать скачать) {sendIntent (скачать); natificationBuilder.setProgress (100, download.getProgress (), false); natificationBuilder.setContentText (stringUtils.getDatasize (download.getCurrentFilesize ()) + "/" + stringUtils.getDatasize (download.getTotalFilesize ())); natificationManager.notify (0, nобонстрирование builder.build ()); } private void sendIntent (скачать скачать) {intent intent = new Intent (mainActivity.message_progress); intent.putextra ("Скачать", скачать); Localbroadcastmanager.getinstance (downloadservice.this) .sendbroadcast (намерение); } @Override public void ontaskRemoved (intent rootintent) {notificationManager.cancel (0); }}Код MainActivity:
открытый класс mainActivity расширяет appcompatactivity {public static final String message_progress = "message_progress"; private appcompatbutton btn_download; Частный прогресс в базе; Private TextView progress_text; Частный Broadcastreiver broadcastreceiver = new Broadcastreceiver () {@Override public void OnReceive (контекст контекста, намерение) {if (intent.getAction (). equals (message_progress)) {download = intent.getparcebleextra ("загрузка"); Progress.setProgress (download.getProgress ()); if (download.getprogress () == 100) {progress_text.settext ("file Downlock Complete"); } else {progress_text.settext (stringutils.getDatasize (download.getCurrentFilesize ()) + "/" + stringUtils.getDatasize (скачать.gettotalFilesize ())); }}}}}}}; @Override Protected void Oncreate (Bundle SavedInstanceState) {super.oncreate (savedInstanceState); setContentView (r.layout.activity_main); btn_download = (appcompatbutton) findviewbyid (r.id.btn_download); Прогресс = (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); Starstervice (намерение);}}); } private void RegisterReceiver () {localbroadcastmanager bmanager = localbroadcastmanager.getInstance (this); Intentfilter intentfilter = new IntentFilter (); intentfilter.addaction (message_progress); Bmanager.RegisterReceiver (Broadcastreceiver, Intentfilter); }}Исходный код этой статьи: Модернизация rxjava реализация файла загрузки
Выше всего содержание этой статьи. Я надеюсь, что это будет полезно для каждого обучения, и я надеюсь, что все будут поддерживать Wulin.com больше.