欧美一级特黄大片做受成人-亚洲成人一区二区电影-激情熟女一区二区三区-日韩专区欧美专区国产专区

Retrofit+Rxjava如何實現(xiàn)帶進度顯示的下載文件-創(chuàng)新互聯(lián)

這篇文章將為大家詳細講解有關(guān)Retrofit+Rxjava如何實現(xiàn)帶進度顯示的下載文件,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

創(chuàng)新互聯(lián)公司是專業(yè)的揭西網(wǎng)站建設(shè)公司,揭西接單;提供網(wǎng)站設(shè)計、網(wǎng)站建設(shè),網(wǎng)頁設(shè)計,網(wǎng)站設(shè)計,建網(wǎng)站,PHP網(wǎng)站建設(shè)等專業(yè)做網(wǎng)站服務(wù);采用PHP框架,可快速的進行揭西網(wǎng)站開發(fā)網(wǎng)頁制作和功能擴展;專業(yè)做搜索引擎喜愛的網(wǎng)站,專業(yè)的做網(wǎng)站團隊,希望更多企業(yè)前來合作!

具體內(nèi)容如下

本文采用 :retrofit + rxjava

1.引入:

//rxJava
 compile 'io.reactivex:rxjava:latest.release'
 compile 'io.reactivex:rxandroid:latest.release'
 //network - squareup
 compile 'com.squareup.retrofit2:retrofit:latest.release'
 compile 'com.squareup.retrofit2:adapter-rxjava:latest.release'
 compile 'com.squareup.okhttp3:okhttp:latest.release'
 compile 'com.squareup.okhttp3:logging-interceptor:latest.release'

2.增加下載進度監(jiān)聽:

public interface DownloadProgressListener {
 void update(long bytesRead, long contentLength, boolean done);
}
public class DownloadProgressResponseBody extends ResponseBody {

 private ResponseBody responseBody;
 private DownloadProgressListener progressListener;
 private BufferedSource bufferedSource;

 public DownloadProgressResponseBody(ResponseBody responseBody,
          DownloadProgressListener 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;
 }

 private Source source(Source source) {
  return new ForwardingSource(source) {
   long totalBytesRead = 0L;

   @Override
   public long read(Buffer sink, long byteCount) throws IOException {
    long bytesRead = super.read(sink, byteCount);
    // read() returns the number of bytes read, or -1 if this source is exhausted.
    totalBytesRead += bytesRead != -1 ? bytesRead : 0;

    if (null != progressListener) {
     progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1);
    }
    return bytesRead;
   }
  };

 }
}
public class DownloadProgressInterceptor implements Interceptor {

 private DownloadProgressListener listener;

 public DownloadProgressInterceptor(DownloadProgressListener listener) {
  this.listener = listener;
 }

 @Override
 public Response intercept(Chain chain) throws IOException {
  Response originalResponse = chain.proceed(chain.request());

  return originalResponse.newBuilder()
    .body(new DownloadProgressResponseBody(originalResponse.body(), listener))
    .build();
 }
}

3.創(chuàng)建下載進度的元素類:

public class Download implements Parcelable {

 private int progress;
 private long currentFileSize;
 private long totalFileSize;

 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 describeContents() {
  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 createFromParcel(Parcel source) {
   return new Download(source);
  }

  @Override
  public Download[] newArray(int size) {
   return new Download[size];
  }
 };
}

4.下載文件網(wǎng)絡(luò)類:

public interface DownloadService {

 @Streaming
 @GET
 Observable<ResponseBody> download(@Url String url);
}

注:這里@Url是傳入完整的的下載URL;不用截取

public class DownloadAPI {
 private static final String TAG = "DownloadAPI";
 private static final int DEFAULT_TIMEOUT = 15;
 public Retrofit retrofit;


 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, final File file, Subscriber subscriber) {
  Log.d(TAG, "downloadAPK: " + url);

  retrofit.create(DownloadService.class)
    .download(url)
    .subscribeOn(Schedulers.io())
    .unsubscribeOn(Schedulers.io())
    .map(new Func1<ResponseBody, InputStream>() {
     @Override
     public InputStream call(ResponseBody responseBody) {
      return responseBody.byteStream();
     }
    })
    .observeOn(Schedulers.computation())
    .doOnNext(new Action1<InputStream>() {
     @Override
     public void call(InputStream inputStream) {
      try {
       FileUtils.writeFile(inputStream, file);
      } catch (IOException e) {
       e.printStackTrace();
       throw new CustomizeException(e.getMessage(), e);
      }
     }
    })
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(subscriber);
 }


}

然后就是調(diào)用了:

該網(wǎng)絡(luò)是在service里完成的

public class DownloadService extends IntentService {
 private static final String TAG = "DownloadService";

 private NotificationCompat.Builder notificationBuilder;
 private NotificationManager notificationManager;


 private String apkUrl = "http://download.fir.im/v2/app/install/595c5959959d6901ca0004ac?download_token=1a9dfa8f248b6e45ea46bc5ed96a0a9e&source=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 File")
    .setAutoCancel(true);

  notificationManager.notify(0, notificationBuilder.build());

  download();
 }

 private void download() {
  DownloadProgressListener listener = 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(download);
   }
  };
  File outputFile = new File(Environment.getExternalStoragePublicDirectory
    (Environment.DIRECTORY_DOWNLOADS), "file.apk");
  String baseUrl = StringUtils.getHostName(apkUrl);

  new DownloadAPI(baseUrl, listener).downloadAPK(apkUrl, outputFile, new Subscriber() {
   @Override
   public void onCompleted() {
    downloadCompleted();
   }

   @Override
   public void onError(Throwable e) {
    e.printStackTrace();
    downloadCompleted();
    Log.e(TAG, "onError: " + e.getMessage());
   }

   @Override
   public void onNext(Object o) {

   }
  });
 }

 private void downloadCompleted() {
  Download download = new Download();
  download.setProgress(100);
  sendIntent(download);

  notificationManager.cancel(0);
  notificationBuilder.setProgress(0, 0, false);
  notificationBuilder.setContentText("File Downloaded");
  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 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);
 }
}

MainActivity代碼:

public class MainActivity extends AppCompatActivity {

 public static final String MESSAGE_PROGRESS = "message_progress";

 private AppCompatButton btn_download;
 private ProgressBar progress;
 private TextView progress_text;


 private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {

   if (intent.getAction().equals(MESSAGE_PROGRESS)) {

    Download download = intent.getParcelableExtra("download");
    progress.setProgress(download.getProgress());
    if (download.getProgress() == 100) {

     progress_text.setText("File Download Complete");

    } else {

     progress_text.setText(StringUtils.getDataSize(download.getCurrentFileSize())
       +"/"+
       StringUtils.getDataSize(download.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);

  registerReceiver();

  btn_download.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {
    Intent intent = new Intent(MainActivity.this, DownloadService.class);
    startService(intent);
   }
  });
 }

 private void registerReceiver() {

  LocalBroadcastManager bManager = LocalBroadcastManager.getInstance(this);
  IntentFilter intentFilter = new IntentFilter();
  intentFilter.addAction(MESSAGE_PROGRESS);
  bManager.registerReceiver(broadcastReceiver, intentFilter);

 }
}

關(guān)于“Retrofit+Rxjava如何實現(xiàn)帶進度顯示的下載文件”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。

新聞標題:Retrofit+Rxjava如何實現(xiàn)帶進度顯示的下載文件-創(chuàng)新互聯(lián)
網(wǎng)站路徑:http://aaarwkj.com/article38/cdppsp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供ChatGPT微信公眾號、品牌網(wǎng)站建設(shè)、小程序開發(fā)、品牌網(wǎng)站制作網(wǎng)站策劃

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

h5響應(yīng)式網(wǎng)站建設(shè)
久久精品一区二区三区不卡| 亚洲精品亚洲一区亚洲二区| 中文字幕精品免费日韩在线| 国产成人一区二区三区综合区 | 清纯唯美校园春色亚洲激情 | 99热精品成人免费观看| va精品人妻一区二区三区| 午夜日本大胆裸体艺术| 精品人妻一区二区三区久久91 | 国产熟女系列一区二区三区 | 亚洲一区二区三区在线观看| 欧美激情在线精品一区二区| 亚洲专区综合红桃av| 国产尤物直播在线观看| 亚洲国产中文日韩欧美在线| 一区二区三区在线观看日韩| 中文字幕伦理一区二区| 长腿丝袜美女亚洲一区二区| 久久成人a毛片免费观看网站| 97国产精品视频在线观看| 一区二区三区亚洲精品在线| 青青草青娱乐免费在线视频| 最新中文字幕成人在线观看| 日本福利资源在线观看| 成人免费在线视频不卡| 正在播放老肥熟妇露脸| 91麻豆精品在线观看| 91国产性感美女视频| 蜜桃av在线播放视频| 亚洲婷婷久久一区二区| 欧美日韩国产精品一区二区三区| 自拍偷拍亚洲另类激情| 国产亚洲精品美女视频| 综合av在线一区天堂| 国产污视频网站在线观看| 国产我和子的乱视频亲生| 清纯唯美亚洲自拍第一页| 国产成人精品视频午夜蜜蜂| 午夜国产激情福利网站| 亚洲国产熟女一区二区三| av欧美激情在线观看|