تشترك هذه المقالة في ملف تنزيل تنزيل تطبيق RXJAVA المحدد لرجوعك. المحتوى المحدد كما يلي
تستخدم هذه المقالة: retrofit + rxjava
1.
// rxjava compile 'io.reactivex: rxjava: tirs.release' compile 'io.reactivex: rxAndroid: tirs.Release' // network - squaruup compile 'com.squareup.retrofit2: retrofit: tirs.release' compile 'com.squareup 'com.squareup.retrofit2: adapter-rxjava: tirs.Release' compile 'com.squareup.okhttp3: okhttp: tirs.release' compile 'com.squareup.okhttp3: logging-interceptor: أحدث.
2. زيادة تنزيل مراقبة التقدم:
الواجهة العامة DownloadProgressListener {void update (BytesRead طويل ، محتوى طويل ، Boolean Done) ؛} الطبقة العامة downloadProgressResponsebody يمتد استجابة {private responsebodybody ؛ Private ProgrogressListener ProgressListener ؛ خاص BufferedSource BufferedSource ؛ Public DownloadProgressPonsePonseBody (ResponseBody Response ، DownloadProgressListener ProgressListener) {this.responseBody = responseBody ؛ this.progressListener = ProgressListener ؛ } Override Public MediaType contentType () {return responseBody.contentType () ؛ } Override Public ContentLength () {return responsebody.contentLength () ؛ } Override Public BufferedSource Source () {if (BufferedSource == null) {bufferedSource = Okio.buffer (source (responsebody.source ())) ؛ } إرجاع BufferedSource ؛ } مصدر خاص (مصدر المصدر) {return New TalleringingSource (Source) {Long TotalByTesRead = 0L ؛ Override Public Read Long (Sink Buffer ، Long Bytecount) يلقي ioException {long bytesread = super.read (sint ، bytecount) ؛ // read () إرجاع عدد البايتات القراءة ، أو -1 إذا تم استنفاد هذا المصدر. TotalBytesRead += bytesread! = -1؟ bytesread: 0 ؛ if (null! = progressListener) {ProgressListener.update (TotalByTesRead ، responseBody.contentLength () ، bytesRead == -1) ؛ } إرجاع bytesread ؛ }} ؛ }} الفئة العامة DownloadProgressInterceptor تنفذ Interceptor {Private DownloadProgressListener Beasher ؛ Public DownloadProgressInterNector (downloadProgressRistener Bearner) {this.listener = beather ؛ } Override Intercept Response (سلسلة السلسلة) يلقي ioException {استجابة OriginalResponse = chain.proceed (chain.request ()) ؛ return OrventionResponse.newBuilder () .body (تنزيل جديد progressponsebody (OriginalResponse.body () ، المستمع)) .build () ؛ }}3. إنشاء فئة العناصر للتنزيل التقدم:
تنزيل الطبقة العامة ينفذ Parcelable {Private Int Progress ؛ Private Long Currentfilesize ؛ TotalFilesize الطويل الخاص ؛ Public int getProgress () {return progress ؛ } public void setProgress (int progress) {this.progress = progress ؛ } public getCurrentFilesize () {return CurrentFilesize ؛ } public void setCurrentFilesize (currentfilesize long) {this.currentFilesize = currentFilesize ؛ } public getTotalFilesize () {return totalFilesize ؛ } public void settoTalFilesize (totalFilesize long) {this.totalfilesize = totalFilesize ؛ } Override public int distracteContents () {return 0 ؛ } Override public void writetoparcel (Parcel Dest ، int flags) {dest.writeint (this.progress) ؛ Dest.Writelong (this.currentFilesize) ؛ Dest.Writelong (this.totalfilesize) ؛ } التنزيل العام () {} تنزيل محمي (parcel in) {this.progress = in.readint () ؛ this.currentFilesize = in.readlong () ؛ this.totalfilesize = in.readlong () ؛ } public static Final Parcelable.Creator <download> creator = new parcelable.creator <تنزيل> () {Override Public Download CreateFromParcel (Parcel Source) {return new download (source) ؛ } Override Public Download [] NewArray (int size) {return new download [size] ؛ }} ؛}4. قم بتنزيل فئة شبكة الملفات:
الواجهة العامة تنزيل { @streaminggget قابلة للملاحظة <riptionBody> تنزيل (url string url) ؛}ملاحظة: هنا url هو عنوان URL تنزيل كامل ؛ لا اعتراض
الفئة العامة DownloadApi {private static Final String Tag = "DownloadApi" ؛ خاص ثابت نهائي int default_timeout = 15 ؛ التحديثية العامة التعديل التحديثي. Public DownloadApi (url url ، downloadProgressListener beasher) {downloadProgressInterceptor interceptor = new DownloadProgressInterceptor (مستمع) ؛ عميل OKHTTPCLIENT = جديد OKHTTPCLIENT.BUILDER () .AddInterceptor (اعتراض) .RETRYONCONNECTIONFAILURE (صواب) .CONNECTTIMEOUT (default_timeout ، timeUnit.seconds) .build () ؛ retrofit = جديد retrofit.builder () .baseurl (url) .client (client) .addcalladapterfactory (rxjavacalladapterfactory.create ()) .build () ؛ } public void downloadAPK (@nonull string url ، ملف الملف النهائي ، مشترك المشترك) {log.d (tag ، "downloadapk:" + url) ؛ retrofit.create (downloadservice.class) .Download (url) .SubScribeon (Schedulers.io ()) .Unsubscribeon (Schedulers.io ()) .map (new func1 <striptebody ، inputStream> () .Observeon (Schedulers.computation ()) .doonnext (إجراء جديد 1 <PestStream> () {Override public void call (inputStream inputStream) {try {fileUtils.writeFile (inputStream ، file) ؛} catch (ioException e) { .Observeon (AndroidsChedulers.MainThread ()) .Subscribe (مشترك) ؛ }} ثم يطلق عليه:
تتم الشبكة في الخدمة
تنزيلات الفئة العامة تمتد intentservice {private static final string tag = "downloadService" ؛ إعلام خاص compat.builder الإخطار بويلدر ؛ إعلام خاص الإخطار سلسلة خاصة apkurl = "http://download.fir.im/v2/app/install/5959595959d6901ca0004ac؟download_token=1a9dfa8f248b6e45e46bc5ed96a9e&source=update" ؛ التنزيلات العامة () {super ("DownloadService") ؛ } override void onhandleintent (intent intent) {detificationManager = (dotificationManager) getSystemService (context.notification_service) ؛ DetificationBuilder = New AssificationCompat.Builder (هذا) .SetSmallicon ( الإخطار manager.notify (0 ، الإخطار builder.build ()) ؛ تحميل()؛ } private void download () {downloadProgressListener leader = new DownloadProgressListener () {Override public void update (long bytesread ، long contentLength ، boolean done) {download download = new download () ؛ download.settotalfilesize (contentLength) ؛ download.setCurrentFilesize (bytesread) ؛ int progress = (int) ((bytesread * 100) / contentLength) ؛ download.setProgress (Progress) ؛ SendNotification (تنزيل) ؛ }} ؛ File OutputFile = ملف جديد (بيئة. String baseurl = stringUtils.gethostName (apkurl) ؛ New DownloadApi (baseurl ، المستمع) .downloadapk (apkurl ، outputfile ، مشترك جديد () {Override public void onCompleted () {downloadCompleted () ؛} @over void onerror (onerable e) {e.printstacktrace () ؛ } Override public void onnext (Object o) {}}) ؛ } private void downloadCompleted () {download download = new download () ؛ download.setProgress (100) ؛ sendIntent (تنزيل) ؛ إخطار Manager.cancel (0) ؛ الإخطار builder.setProgress (0 ، 0 ، خطأ) ؛ الإخطار builder.setContentText ("ملف تنزيل") ؛ الإخطار manager.notify (0 ، الإخطار builder.build ()) ؛ } private void sendNotification (تنزيل تنزيل) {sendIntent (download) ؛ الإخطار builder.setProgress (100 ، download.getProgress () ، false) ؛ الإخطار builder.setContentText (StringUtils.getDatasize (download.getCurrentFilesize ()) + "/" + stringUtils.getDatasize (download.getTotalFilesize ())) ؛ الإخطار manager.notify (0 ، الإخطار builder.build ()) ؛ } private void sendIntent (تنزيل تنزيل) {intent intent = new intent (MainActivity.message_progress) ؛ intent.putextra ("download" ، download) ؛ localbroadcastmanager.getInstance (DownloadService.This) .SendBroadcast (نية) ؛ } Override public void ontaskRemoved (intent rootIntent) {detificationManager.cancel (0) ؛ }}رمز النشاط الرئيسي:
يمتد النشاط الرئيسي للطبقة العامة AppCompatActivity {message static string message_progress = "message_progress" ؛ appcompatbutton الخاص btn_download ؛ تقدم ProgressBar الخاص ؛ TextView Progress_Text ؛ برودكاستير برودكاستير الخاص = جديد برودكاستيرريفر () {Override public void onReceive (سياق السياق ، النية القضائية) {if (intent.getAction (). equals (message_progress)) {download = intent.getParcelableAxtra ("download") ؛ Progress.SetProgress (download.getProgress ()) ؛ if (download.getProgress () == 100) {progress_text.settext ("File Download Complete") ؛ } آخر {progress_text.settext (stringUtils.getDatasize (download.getCurrentFilesize ()) + "/" + stringUtils.getDatasize (download.getTotalFilesize ())) ؛ }}}}}}} ؛ Override محمية void onCreate (backdle SaveInstancestate) {super.oncreate (SaveInstancestate) ؛ 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.Tis ، DownloadService.Class) ؛ startervice (intent) ؛}}) ؛ } private void registerReceiver () {localbroadcastmanager bmanager = localbroadcastmanager.getInstance (this) ؛ intentFilter intentFilter = new IntentFilter () ؛ intentFilter.addacte (message_progress) ؛ bmanager.registerReceiver (Broadcastreceiver ، intentFilter) ؛ }}رمز المصدر لهذه المقالة: تحديث ملف تنفيذ تطبيق Rxjava
ما سبق هو كل محتوى هذه المقالة. آمل أن يكون ذلك مفيدًا لتعلم الجميع وآمل أن يدعم الجميع wulin.com أكثر.