Downloader.java
3.06 KB
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
package com.huaheng.download;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;
import java.io.File;
import java.util.HashMap;
/**
* Created by youjie on 2018/3/28.
*/
public class Downloader {
private final static String TAG = "Downloader";
private final static int MAX_RERTY_TIMES = 0;
private DownloadCallback mCallback = null;
private HashMap<String, Callback.Cancelable> mDownloads = null;
public Downloader() {
mDownloads = new HashMap<>();
}
public void download(final String url, String fileName, String path) {
RequestParams requestParams = new RequestParams(url);
requestParams.setSaveFilePath(path + fileName);
requestParams.setAutoRename(true);
requestParams.setMaxRetryCount(MAX_RERTY_TIMES);
DownloadProgressCallback mDownloadProgressCallback = new DownloadProgressCallback(fileName);
Callback.Cancelable cancelable = x.http().get(requestParams, mDownloadProgressCallback);
mDownloads.put(fileName, cancelable);
}
private class DownloadProgressCallback implements Callback.ProgressCallback<File> {
private String fileName;
private DownloadCallback callback;
DownloadProgressCallback(String fileName) {
this.fileName = fileName;
}
public void setProgressListener(DownloadCallback callback) {
this.callback = callback;
}
public String getFileName() {
return fileName;
}
@Override
public void onWaiting() {
}
@Override
public void onStarted() {
if(mCallback != null) {
mCallback.onStart(getFileName());
}
}
@Override
public void onLoading(long total, long current, boolean isDownloading) {
if(mCallback != null) {
int progress = (int)(current * 100 / total);
mCallback.onLoading(getFileName(), progress, isDownloading);
}
}
@Override
public void onSuccess(File result) {
if(mCallback != null) {
mCallback.onSuccess(getFileName(), result);
}
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
if(mCallback != null) {
String msg = ex.getMessage();
mCallback.onError(getFileName(), msg);
}
}
@Override
public void onCancelled(CancelledException cex) {
if(mCallback != null) {
mCallback.onCancelled(getFileName());
}
}
@Override
public void onFinished() {
}
}
public void setDownloadCallback(DownloadCallback callback) {
mCallback = callback;
}
public void removeDownloadWorker(String fileName) {
if(fileName == null) {
return;
}
Callback.Cancelable cancelable = mDownloads.get(fileName);
if(cancelable != null) {
cancelable.cancel();
}
}
}