基於Retrofit+Okio+RxBus實現文件下載(帶下載進度)


轉載地址:http://www.tailyou.site/2016/06/22/%E5%9F%BA%E4%BA%8ERetrofit-Okio-RxBus%E5%AE%9E%E7%8E%B0%E6%96%87%E4%BB%B6%E4%B8%8B%E8%BD%BD%EF%BC%88%E5%B8%A6%E4%B8%8B%E8%BD%BD%E8%BF%9B%E5%BA%A6%EF%BC%89/#rd?sukey=3997c0719f15152082403b18fc5108edcba8ef69abbe1891a9450ae7921f97ab7f9f472fd055d7b55360001d25a6d031


一、前言

  Retrofit是一個非常優秀、非常流行的簡化HTTP請求的庫,有個小的不足是下載文件時,沒有提供顯示文件下載進度的回調,這在下載文件時無疑會影響用戶體驗,本文基於Retrofit+Okio+RxBus實現了帶下載進度的文件下載功能。

二、效果

三、實現過程

3.1 下載文件的代碼

  接下來我們從代碼入手,分析如何使用及其實現原理。假如現在要下載 http://hengdawb-app.oss-cn-hangzhou.aliyuncs.com/app-debug.apk 對應的APK文件,對應代碼如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
String baseUrl = "http://hengdawb-app.oss-cn-hangzhou.aliyuncs.com/";
String fileName = "app-debug.apk";
String fileStoreDir = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "M_DEFAULT_DIR";
String fileStoreName = fileName;
showLoadingDialog();
FileApi.getInstance(baseUrl).loadFileByName(fileName, new FileCallback(fileStoreDir, fileStoreName) {
@Override
public void onSuccess(File file) {
super.onSuccess(file);
hDialogBuilder.dismiss();
}

@Override
public void progress(long progress, long total) {
updateProgress(progress, total);
}

@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
hDialogBuilder.dismiss();
call.cancel();
}

});
  • baseUrl:是網絡請求基地址,必須以 / 結束;
  • fileName:是文件名,與baseUrl組成完整的下載地址;
  • fileStoreDir:是文件下載後在本地的存儲目錄;
  • fileStoreName:是文件在本地的存儲名稱。

3.2 FileCallback

  下載文件的代碼非常簡單,從上面的代碼中可以看到一個叫FileCallback的類,其中有三個方法需要我們自己實現或重寫,分別是onSuccess(),onFailure(),progress(),progress()方法有兩個參數,progress和total,分別表示文件已下載的大小和總大小,我們只需要將這兩個參數不斷更新到UI上即可。FileCallback的代碼如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package com.hengda.tailyou.retrofitfiledownload.fileload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
* 作者:Tailyou (祝文飛)
* 時間:2016/4/5 08:52
* 郵箱:[email protected]
* 描述:Retrofit 文件下載回調
*/

public abstract class FileCallback implements Callback<ResponseBody> {

/**
* 訂閱下載進度
*/

private CompositeSubscription rxSubscriptions = new CompositeSubscription();
/**
* 目標文件存儲的文件夾路徑
*/

private String destFileDir;
/**
* 目標文件存儲的文件名
*/

private String destFileName;

public FileCallback(String destFileDir, String destFileName) {
this.destFileDir = destFileDir;
this.destFileName = destFileName;
subscribeLoadProgress();
}

public void onSuccess(File file) {
unsubscribe();
}

public abstract void progress(long progress, long total);

@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
saveFile(response);
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* 保存
*
* @param response
* @return
* @throws IOException
*/

public File saveFile(Response<ResponseBody> response) throws IOException {
InputStream is = null;
byte[] buf = new byte[2048];
int len;
FileOutputStream fos = null;
try {
is = response.body().byteStream();
File dir = new File(destFileDir);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, destFileName);
fos = new FileOutputStream(file);
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
}
fos.flush();
onSuccess(file);
return file;
} finally {
try {
if (is != null) is.close();
} catch (IOException e) {
}
try {
if (fos != null) fos.close();
} catch (IOException e) {
}
}
}

/**
* 訂閱文件下載進度
*/

private void subscribeLoadProgress() {
rxSubscriptions.add(RxBus.getDefault()
.toObservable(FileLoadEvent.class)
.onBackpressureBuffer()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<FileLoadEvent>() {
@Override
public void call(FileLoadEvent fileLoadEvent) {
progress(fileLoadEvent.getProgress(), fileLoadEvent.getTotal());
}
}));
}

/**
* 取消訂閱,防止內存泄漏
*/

private void unsubscribe() {
if (!rxSubscriptions.isUnsubscribed()) {
rxSubscriptions.unsubscribe();
}
}

}

  代碼比較多,跟下載進度相關的其實非常少,可以看到咱們實現的progress()方法在是在RxBus收到FileLoadEvent後才調用的,熟悉RxBus的人肯定可以想到,下載進度的實時更新是通過以下幾步實現的:

  • 1)RxBus發送FileLoadEvent對象;
  • 2)FileLoadEvent中包含當前下載進度和文件總大小;
  • 3)FileCallback訂閱RxBus發送的FileLoadEvent;
  • 4)根據接收到的FileLoadEvent更新下載Dialog的UI。

3.3 何時何處發送的FileLoadEvent?

  使用Retrofit進行網絡操作時,通常都與OKHttpClient結合使用;我們可以用OKHttpClient來設置連接超時,請求超時,網絡攔截器等。這裏我們也需要使用自己的OKHttpClient,在網絡攔截器中使用我們自定義的ResponseBody。代碼如下:

1
2
3
4
5
6
7
private FileApi(String baseUrl) {
retrofit = new Retrofit.Builder()
.client(initOkHttpClient())

.baseUrl(baseUrl)
.build();
fileService = retrofit.create(FileService.class);

}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* 初始化OkHttpClient
*
* @return
*/

private OkHttpClient initOkHttpClient() {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);

builder.networkInterceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response originalResponse = chain.proceed(chain.request());
return originalResponse
.newBuilder()

.body(new FileResponseBody(originalResponse))
.build();
}

});
return builder.build();
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* 作者:Tailyou (祝文飛)
* 時間:2016/5/30 16:19
* 郵箱:[email protected]
* 描述:
*/

public class FileResponseBody extends ResponseBody {

Response originalResponse;

public FileResponseBody(Response originalResponse) {
this.originalResponse = originalResponse;
}

@Override
public MediaType contentType() {
return originalResponse.body().contentType();
}

@Override
public long contentLength() {
return originalResponse.body().contentLength();
}

@Override
public BufferedSource source() {
return Okio.buffer(new ForwardingSource(originalResponse.body().source()) {
long bytesReaded = 0;

@Override
public long read(Buffer sink, long byteCount) throws IOException {
long bytesRead = super.read(sink, byteCount);
bytesReaded += bytesRead == -1 ? 0 : bytesRead;
RxBus.getDefault().post(new FileLoadEvent(contentLength(), bytesReaded));
return bytesRead;
}
});
}

}

  FileResponseBody重寫了source()方法,在Okio.buffer中處理下載進度相關的邏輯,也是在這個時候發送的FileLoadEvent的,到這裏整個過程就差不多全了。

總結

  其實整個過程並不複雜,總結起來就一下幾點:

  • 1)使用自定義的OKHttpClient,在自定義的FileResponseBody中發送文件下載進度;
  • 2)在FileCallback中訂閱FileLoadEvent;
  • 3)根據FileLoadEvent中的參數,調用progress(),刷新下載UI。

源碼已上傳Github,RetrofitFileDownload


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章