溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

基于Ok+Rxjava+retrofit實(shí)現(xiàn)斷點(diǎn)續(xù)傳下載

發(fā)布時(shí)間:2020-09-17 09:12:04 來(lái)源:腳本之家 閱讀:269 作者:Super_Ks 欄目:編程語(yǔ)言

本文為大家分享了實(shí)現(xiàn)斷點(diǎn)續(xù)傳下載的具體代碼,供大家參考,具體內(nèi)容如下

1、基于Ok+Rxjava實(shí)現(xiàn)斷點(diǎn)續(xù)傳下載

2、基于Ok+Rxjava+Retrofit實(shí)現(xiàn)斷點(diǎn)續(xù)傳下載

上一篇博客中介紹了基于Ok+Rxjava實(shí)現(xiàn)斷點(diǎn)續(xù)傳下載,這一篇給大家介紹下基于Ok+Rxjava+Retrofit實(shí)現(xiàn)斷點(diǎn)續(xù)傳下載,demo下載地址,效果圖跟上一篇圖片一樣,哈哈

基于Ok+Rxjava+retrofit實(shí)現(xiàn)斷點(diǎn)續(xù)傳下載

 說(shuō)下我的大致思路吧(跟上一篇略有不同):根據(jù)文件下載url按照自己定義的規(guī)則生成文件名,判斷本地同路徑下是否存在此文件,如果存在,文件大小與服務(wù)器上獲取的文件大小一致的情況下,則覆蓋本地文件重新下載;如果文件比服務(wù)器獲取的文件大小小,則執(zhí)行斷點(diǎn)下載,從本地文件長(zhǎng)度處開(kāi)始下載。如果文件不存在,則從0字節(jié)開(kāi)始下載。

還有的不同是,這里需要重新ResponseBody的source()方法,在這里監(jiān)聽(tīng)文件下載的進(jìn)度,然后通過(guò)我么自定義的Downloadinterceptor把我們重新的DownloadResponseBody給設(shè)置進(jìn)去,從而完成我們的進(jìn)度監(jiān)聽(tīng)工作。

下面還是上主要代碼:

首先重寫(xiě)ResponseBody

public class DownloadResponseBody extends ResponseBody {
 private ResponseBody responseBody;
 
 //進(jìn)度回調(diào)接口
 private DownFileCallback downFileCallback;
 
 private BufferedSource bufferedSource;
 private String downUrl;
 
 
 public DownloadResponseBody(ResponseBody responseBody, DownFileCallback downFileCallback, String downUrl) {
 this.responseBody = responseBody;
 this.downFileCallback = downFileCallback;
 this.downUrl = downUrl;
 }
 
 @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;
 File file = new File(DownloadManager.getInstance().getTemporaryName(downUrl));
 
 @Override
 public long read(Buffer sink, long byteCount) throws IOException {
 long bytesRead = super.read(sink, byteCount);
 totalBytesRead += bytesRead != -1 ? bytesRead : 0;
 if (null != downFileCallback) {
 if (bytesRead != -1) {
 long loacalSize = file.length();//本地已下載的長(zhǎng)度
 long trueTotal = loacalSize + responseBody.contentLength() - totalBytesRead;//文件真實(shí)長(zhǎng)度
 downFileCallback.onProgress(trueTotal,loacalSize);
 } else {
 
 }
 
 }
 return bytesRead;
 }
 };
 
 }
}

重寫(xiě)Interceptor

public class Downloadinterceptor implements Interceptor {
 
 private DownFileCallback downFileCallback;
 
 private String downUrl;
 
 public Downloadinterceptor(DownFileCallback listener,String downUrl) {
 this.downFileCallback = listener;
 this.downUrl = downUrl;
 }
 
 @Override
 public Response intercept(Chain chain) throws IOException {
 Response response = chain.proceed(chain.request());
 
 return response.newBuilder()
 .body(new DownloadResponseBody(response.body(), downFileCallback,downUrl))
 .build();
 }
}

然后我們的service

public interface HttpService {
 
 /*大文件需要加入Streaming這個(gè)判斷,防止下載過(guò)程中寫(xiě)入到內(nèi)存中,造成oom*/
 @Streaming
 @GET
 Observable<ResponseBody> download(@Header("range") String start, @Url String url);
}

接下來(lái)我們的DownloadManager中download方法

 /**
 * 開(kāi)始下載
 * @param url 下載地址
 * @param downFileCallback 進(jìn)度回調(diào)接口
 */
 public void download(final String url, final DownFileCallback downFileCallback) {
 /*正在下載不處理*/
 if (url == null || submap.get(url) != null) {
 return;
 }
 
 Downloadinterceptor interceptor = new Downloadinterceptor(downFileCallback, url);
 okHttpClient = new OkHttpClient.Builder()
 .addInterceptor(interceptor)
 .build();
 Retrofit retrofit = new Retrofit.Builder()
 .client(okHttpClient)
 .baseUrl("http://imtt.dd.qq.com")
 .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
 .build();
 final HttpService httpservice = retrofit.create(HttpService.class);
 
 ProgressDownSubscriber subscriber =
 Observable.just(url)
 .flatMap(new Function<String, ObservableSource<DownloadInfo>>() {
 @Override
 public ObservableSource<DownloadInfo> apply(String s) throws Exception {
 return Observable.just(createDownInfo(s));
 }
 })
 .map(new Function<DownloadInfo, DownloadInfo>() {
 @Override
 public DownloadInfo apply(DownloadInfo s) throws Exception {
 return getRealFileName(s);
 }
 })
 .flatMap(new Function<DownloadInfo, Observable<ResponseBody>>() {
 @Override
 public Observable<ResponseBody> apply(DownloadInfo downInfo) throws Exception {
 return httpservice.download("bytes=" + downInfo.getProgress() + "-", downInfo.getUrl());
 }
 })//下載
 .map(new Function<ResponseBody, DownloadInfo>() {
 @Override
 public DownloadInfo apply(ResponseBody responsebody) {
 try {
 return writecache(responsebody, url);
 } catch (IOException e) {
 //*失敗拋出異常*//
 e.printStackTrace();
 }
 return null;
 }
 })
 .observeOn(AndroidSchedulers.mainThread())//在主線程回調(diào)
 .subscribeOn(Schedulers.io())//在子線程執(zhí)行
 .subscribeWith(new ProgressDownSubscriber<DownloadInfo>() {
 @Override
 public void onNext(DownloadInfo downInfo) {
 downFileCallback.onSuccess(downInfo);
 submap.remove(downInfo.getUrl());
 }
 
 @Override
 public void onError(Throwable t) {
 downFileCallback.onFail(t.getMessage());
 submap.remove(url);
 }
 });
 
 
 submap.put(url, subscriber);
 }

然后暫停操作:

 /**
 * 暫停下載
 */
 public void stop(String url) {
 if (url == null) return;
 if (submap.containsKey(url)) {
 ProgressDownSubscriber subscriber = submap.get(url);
 subscriber.dispose();
 submap.remove(url);
 }
 }

從服務(wù)器獲取文件長(zhǎng)度

/**
 * 從服務(wù)器獲取文件長(zhǎng)度
 *
 * @param downloadUrl
 * @return
 */
 private long getContentLength(String downloadUrl) {
 Request request = new Request.Builder()
 .url(downloadUrl)
 .build();
 try {
 Response response = mClient.newCall(request).execute();
 if (response != null && response.isSuccessful()) {
 long contentLength = response.body().contentLength();
 response.close();
 return contentLength == 0 ? DownloadInfo.TOTAL_ERROR : contentLength;
 }
 } catch (IOException e) {
 e.printStackTrace();
 }
 return DownloadInfo.TOTAL_ERROR;
 }

從服務(wù)器獲取文件長(zhǎng)度的時(shí)候注意一下,Android P之后,也就是api 28以上禁止明文網(wǎng)絡(luò)傳輸。需要在你的AndroidManifest中的application標(biāo)簽中聲明"android:usesCleartextTraffic="true",允許應(yīng)用進(jìn)行明文傳輸。

使用方法:首先要獲取sd卡權(quán)限

DownloadManager.getInstance().downloadPath(本地存放地址).download(url1, new DownFileCallback() {
 @Override
 public void onSuccess(DownloadInfo info) {
 
 Toast.makeText(MainActivity.this, url1 + "下載完成", Toast.LENGTH_SHORT).show();
 }
 
 @Override
 public void onFail(String msg) {
 Toast.makeText(MainActivity.this, url1 + "下載失敗", Toast.LENGTH_SHORT).show();
 }
 
 @Override
 public void onProgress(final long totalSize, final long downSize) {
 // 需要注意的是,如果文件總大小為50M,已下載的大小為10M,
 // 再次下載時(shí)onProgress返回的totalSize是文件總長(zhǎng)度
 // 減去 已下載大小 10M, 即40M,downSize為本次下載的已下載量
 // 好消息是,我已經(jīng)在內(nèi)部做過(guò)處理,放心使用吧,但是這個(gè)問(wèn)題大家還是要知道的
 
 runOnUiThread(new Runnable() {
 @Override
 public void run() {
 int progress = (int) (downSize * 100 / totalSize);
 progress1.setProgress(progress);
 }
 });
 }
 });

好了今天就到這里,希望能幫到大家,這對(duì)我來(lái)說(shuō)也是一種加深印象的筆記。

demo下載地址

github地址:DownManager  歡迎star

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI