list) {
51 | mContext = context;
52 | mListData = list;
53 | mDownloadManager = DownloadManager.getInstance();
54 | }
55 |
56 | @Override
57 | public CViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
58 | View itemView = LayoutInflater.from(mContext).inflate(R.layout.list_item, parent, false);
59 | return new CViewHolder(itemView);
60 | }
61 |
62 | @Override
63 | public void onBindViewHolder(final CViewHolder holder, final int position) {
64 |
65 | final TestEntity entity = mListData.get(holder.getAdapterPosition());
66 | holder.titleView.setText(entity.getTitle());
67 |
68 | if(TextUtils.isEmpty( entity.getUrl())){
69 | entity.setUrl("the item of " + holder.getAdapterPosition() + " is empty url...");
70 | }
71 | holder.itemView.setTag(entity.getUrl());
72 | String taskId = String.valueOf(entity.getUrl().hashCode());
73 | DownloadTask itemTask = mDownloadManager.getTask(taskId);
74 |
75 | if (itemTask == null) {
76 | holder.downloadButton.setText(R.string.start);
77 | holder.progressView.setText("0");
78 | holder.progressBar.setProgress(0);
79 | } else {
80 | TaskEntity taskEntity = itemTask.getTaskEntity();
81 | int status = taskEntity.getTaskStatus();
82 | responseUIListener(itemTask, holder);
83 | String progress = getPercent(taskEntity.getCompletedSize(), taskEntity.getTotalSize());
84 | switch (status) {
85 | case TASK_STATUS_INIT:
86 | boolean isPause = mDownloadManager.isPauseTask(taskEntity.getTaskId());
87 | boolean isFinish = mDownloadManager.isFinishTask(taskEntity.getTaskId());
88 | holder.downloadButton.setText(isFinish ? R.string.delete : !isPause ? R.string.start : R.string.resume);
89 | holder.progressBar.setProgress(Integer.parseInt(progress));
90 | holder.progressView.setText(progress);
91 | break;
92 | case TASK_STATUS_QUEUE:
93 | holder.downloadButton.setText(R.string.queue);
94 | holder.progressBar.setProgress(Integer.parseInt(progress));
95 | holder.progressView.setText(progress);
96 | break;
97 | case TASK_STATUS_CONNECTING:
98 | holder.downloadButton.setText(R.string.connecting);
99 | holder.progressBar.setProgress(Integer.parseInt(progress));
100 | holder.progressView.setText(progress);
101 | break;
102 | case TASK_STATUS_DOWNLOADING:
103 | holder.downloadButton.setText(R.string.pause);
104 | holder.progressBar.setProgress(Integer.parseInt(progress));
105 | holder.progressView.setText(progress);
106 | break;
107 | case TASK_STATUS_PAUSE:
108 | holder.downloadButton.setText(R.string.resume);
109 | holder.progressBar.setProgress(Integer.parseInt(progress));
110 | holder.progressView.setText(progress);
111 | break;
112 | case TASK_STATUS_FINISH:
113 | holder.downloadButton.setText(R.string.delete);
114 | holder.progressBar.setProgress(Integer.parseInt(progress));
115 | holder.progressView.setText(progress);
116 | break;
117 | case TASK_STATUS_REQUEST_ERROR:
118 | holder.downloadButton.setText(R.string.retry);
119 | holder.progressBar.setProgress(Integer.parseInt(progress));
120 | holder.progressView.setText(progress);
121 | case TASK_STATUS_STORAGE_ERROR:
122 | holder.downloadButton.setText(R.string.retry);
123 | holder.progressBar.setProgress(Integer.parseInt(progress));
124 | holder.progressView.setText(progress);
125 | break;
126 | }
127 | }
128 |
129 |
130 | holder.downloadButton.setOnClickListener(new View.OnClickListener() {
131 | @Override
132 | public void onClick(View v) {
133 | String url = entity.getUrl();
134 | String taskId = String.valueOf(url.hashCode());
135 | DownloadTask itemTask = mDownloadManager.getTask(taskId);
136 |
137 | if (itemTask == null) {
138 | itemTask = new DownloadTask(new TaskEntity.Builder().url(entity.getUrl()).build());
139 | responseUIListener(itemTask, holder);
140 | mDownloadManager.addTask(itemTask);
141 | } else {
142 | responseUIListener(itemTask, holder);
143 | TaskEntity taskEntity = itemTask.getTaskEntity();
144 | int status = taskEntity.getTaskStatus();
145 | switch (status) {
146 | case TASK_STATUS_QUEUE:
147 | mDownloadManager.pauseTask(itemTask);
148 | break;
149 | case TASK_STATUS_INIT:
150 | mDownloadManager.addTask(itemTask);
151 | break;
152 | case TASK_STATUS_CONNECTING:
153 | mDownloadManager.pauseTask(itemTask);
154 | break;
155 | case TASK_STATUS_DOWNLOADING:
156 | mDownloadManager.pauseTask(itemTask);
157 | break;
158 | case TASK_STATUS_CANCEL:
159 | mDownloadManager.addTask(itemTask);
160 | break;
161 | case TASK_STATUS_PAUSE:
162 | mDownloadManager.resumeTask(itemTask);
163 | break;
164 | case TASK_STATUS_FINISH:
165 | mDownloadManager.cancelTask(itemTask);
166 | break;
167 | case TASK_STATUS_REQUEST_ERROR:
168 | mDownloadManager.addTask(itemTask);
169 | break;
170 | case TASK_STATUS_STORAGE_ERROR:
171 | mDownloadManager.addTask(itemTask);
172 | break;
173 | }
174 | }
175 | }
176 | });
177 | }
178 |
179 |
180 | private void responseUIListener(@NonNull final DownloadTask itemTask, final CViewHolder holder) {
181 |
182 | final TaskEntity taskEntity = itemTask.getTaskEntity();
183 |
184 | itemTask.setListener(new DownloadTaskListener() {
185 |
186 | @Override
187 | public void onQueue(DownloadTask downloadTask) {
188 | if (holder.itemView.getTag().equals(taskEntity.getUrl())) {
189 | holder.downloadButton.setText(R.string.queue);
190 | }
191 | }
192 |
193 | @Override
194 | public void onConnecting(DownloadTask downloadTask) {
195 | if (holder.itemView.getTag().equals(taskEntity.getUrl())) {
196 | holder.downloadButton.setText(R.string.connecting);
197 | }
198 | }
199 |
200 | @Override
201 | public void onStart(DownloadTask downloadTask) {
202 | if (holder.itemView.getTag().equals(taskEntity.getUrl())) {
203 | holder.downloadButton.setText(R.string.pause);
204 | holder.progressBar.setProgress(Integer.parseInt(getPercent(taskEntity.getCompletedSize(), taskEntity.getTotalSize())));
205 | holder.progressView.setText(getPercent(taskEntity.getCompletedSize(), taskEntity.getTotalSize()));
206 | }
207 | }
208 |
209 | @Override
210 | public void onPause(DownloadTask downloadTask) {
211 | if (holder.itemView.getTag().equals(taskEntity.getUrl())) {
212 | holder.downloadButton.setText(R.string.resume);
213 | }
214 | }
215 |
216 | @Override
217 | public void onCancel(DownloadTask downloadTask) {
218 | if (holder.itemView.getTag().equals(taskEntity.getUrl())) {
219 | holder.downloadButton.setText(R.string.start);
220 | holder.progressView.setText("0");
221 | holder.progressBar.setProgress(0);
222 | }
223 | }
224 |
225 | @Override
226 | public void onFinish(DownloadTask downloadTask) {
227 | if (holder.itemView.getTag().equals(taskEntity.getUrl())) {
228 | holder.downloadButton.setText(R.string.delete);
229 | }
230 | }
231 |
232 | @Override
233 | public void onError(DownloadTask downloadTask, int codeError) {
234 | if (holder.itemView.getTag().equals(taskEntity.getUrl())) {
235 |
236 | holder.downloadButton.setText(R.string.retry);
237 | switch (codeError) {
238 | case TASK_STATUS_REQUEST_ERROR:
239 | Toast.makeText(mContext, R.string.request_error, Toast.LENGTH_SHORT).show();
240 | break;
241 | case TASK_STATUS_STORAGE_ERROR:
242 | Toast.makeText(mContext, R.string.storage_error, Toast.LENGTH_SHORT).show();
243 | break;
244 |
245 | }
246 |
247 | }
248 | }
249 | });
250 |
251 | }
252 |
253 | private String getPercent(long completed, long total) {
254 |
255 | if (total > 0) {
256 | double fen = ((double) completed / (double) total) * 100;
257 | DecimalFormat df1 = new DecimalFormat("0");
258 | return df1.format(fen);
259 | }
260 | return "0";
261 | }
262 |
263 | @Override
264 | public int getItemCount() {
265 | return mListData.size();
266 | }
267 |
268 | class CViewHolder extends RecyclerView.ViewHolder {
269 |
270 | @BindView(R.id.list_item_title)
271 | TextView titleView;
272 |
273 | @BindView(R.id.list_item_progress_bar)
274 | ProgressBar progressBar;
275 |
276 | @BindView(R.id.list_item_progress_text)
277 | TextView progressView;
278 |
279 | @BindView(R.id.list_item_state_button)
280 | Button downloadButton;
281 |
282 | CViewHolder(View itemView) {
283 | super(itemView);
284 | ButterKnife.bind(this, itemView);
285 | }
286 | }
287 | }
288 |
--------------------------------------------------------------------------------
/app/src/main/java/com/yuan/downloadmanager/TestEntity.java:
--------------------------------------------------------------------------------
1 | package com.yuan.downloadmanager;
2 |
3 | /**
4 | * Created by Yuan on 9/19/16:2:49 PM.
5 | *
6 | * Description:com.yuan.downloadmanager.TestEntity
7 | */
8 |
9 | public class TestEntity {
10 |
11 | private String title;
12 | private String url;
13 |
14 | public String getTitle() {
15 | return title;
16 | }
17 |
18 | public void setTitle(String title) {
19 | this.title = title;
20 | }
21 |
22 | public String getUrl() {
23 | return url;
24 | }
25 |
26 | public void setUrl(String url) {
27 | this.url = url;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
11 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/list_item.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
11 |
20 |
21 |
27 |
28 |
36 |
37 |
43 |
44 |
49 |
50 |
51 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yuanwenbing/DownloadManager/42203f2cff1fc0c0820242f0401cddd4be0addbc/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yuanwenbing/DownloadManager/42203f2cff1fc0c0820242f0401cddd4be0addbc/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yuanwenbing/DownloadManager/42203f2cff1fc0c0820242f0401cddd4be0addbc/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yuanwenbing/DownloadManager/42203f2cff1fc0c0820242f0401cddd4be0addbc/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yuanwenbing/DownloadManager/42203f2cff1fc0c0820242f0401cddd4be0addbc/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | DownloadManager
3 | 开始
4 | 暂停
5 | 等待
6 | 取消
7 | 继续
8 | 删除
9 | 失败
10 | 重试
11 | 连接中
12 | 等待中
13 | 请求异常
14 | 存储异常
15 |
16 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/test/java/com/yuan/downloadmanager/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.yuan.downloadmanager;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() throws Exception {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 | buildscript {
3 | repositories {
4 | jcenter()
5 | mavenCentral()
6 | }
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:2.2.3'
9 | classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
10 | classpath 'org.greenrobot:greendao-gradle-plugin:3.2.1'
11 | }
12 | }
13 |
14 | allprojects {
15 | repositories {
16 | jcenter()
17 | }
18 | }
19 |
20 | task clean(type: Delete) {
21 | delete rootProject.buildDir
22 | }
23 |
24 |
25 |
--------------------------------------------------------------------------------
/captures/demo.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yuanwenbing/DownloadManager/42203f2cff1fc0c0820242f0401cddd4be0addbc/captures/demo.gif
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | org.gradle.jvmargs=-Xmx1536m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
18 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yuanwenbing/DownloadManager/42203f2cff1fc0c0820242f0401cddd4be0addbc/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Dec 28 10:00:20 PST 2015
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/library/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/library/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'com.novoda.bintray-release'
3 | apply plugin: 'org.greenrobot.greendao'
4 | android {
5 | compileSdkVersion 24
6 | buildToolsVersion "24.0.1"
7 |
8 | defaultConfig {
9 | minSdkVersion 14
10 | targetSdkVersion 24
11 | versionCode 1
12 | versionName "1.1.8"
13 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
14 |
15 | }
16 | buildTypes {
17 | release {
18 | minifyEnabled false
19 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
20 | }
21 | }
22 | lintOptions {
23 | abortOnError false
24 | }
25 |
26 | }
27 | tasks.withType(Javadoc) {
28 | options.addStringOption('Xdoclint:none', '-quiet')
29 | options.addStringOption('encoding', 'UTF-8')
30 | options.addStringOption('charSet', 'UTF-8')
31 | }
32 |
33 |
34 | buildscript {
35 | repositories {
36 | jcenter()
37 | }
38 | dependencies {
39 | classpath 'com.novoda:bintray-release:0.4.0'
40 | }
41 | }
42 |
43 | publish {
44 | userOrg = 'yuanwenbing'
45 | groupId = 'com.yuan.library.dmanager'
46 | artifactId = 'downloadmanager-okhttp-release'
47 | publishVersion = '1.1.8'
48 | desc = 'okhttp downloadmanager'
49 | website = 'https://github.com/yuanwenbing/DownloadManager'
50 | }
51 |
52 | dependencies {
53 | compile fileTree(include: ['*.jar'], dir: 'libs')
54 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
55 | exclude group: 'com.android.support', module: 'support-annotations'
56 | })
57 | compile 'com.android.support:appcompat-v7:24.1.1'
58 | testCompile 'junit:junit:4.12'
59 | compile 'com.squareup.okhttp3:okhttp:3.3.1'
60 | compile 'com.squareup.okhttp3:logging-interceptor:3.0.1'
61 | compile 'com.google.code.gson:gson:2.7'
62 | compile 'org.greenrobot:greendao:3.2.0'
63 | }
64 |
65 |
--------------------------------------------------------------------------------
/library/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/Yuan/Work/adt-bundle-mac/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/library/src/androidTest/java/com/yuan/library/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.yuan.library;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumentation test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() throws Exception {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("com.yuan.library.test", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/library/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/library/src/main/java/com/yuan/library/dmanager/db/DaoManager.java:
--------------------------------------------------------------------------------
1 | package com.yuan.library.dmanager.db;
2 |
3 | import com.yuan.library.dmanager.download.DownloadManager;
4 | import com.yuan.library.dmanager.download.TaskEntity;
5 | import com.yuan.library.dmanager.download.TaskEntityDao;
6 |
7 | import java.util.List;
8 |
9 | /**
10 | * Created by Yuan on 8/17/16.
11 | *
12 | * download database dao
13 | */
14 |
15 | public class DaoManager {
16 |
17 |
18 | private static DaoManager mInstance;
19 |
20 | private DaoManager() {
21 | }
22 |
23 | public static DaoManager instance() {
24 | synchronized (DaoManager.class) {
25 | if (mInstance == null) {
26 | mInstance = new DaoManager();
27 | }
28 | }
29 | return mInstance;
30 | }
31 |
32 | public void insertOrReplace(TaskEntity entity) {
33 | DownloadManager.getInstance().getDaoSession().insertOrReplace(entity);
34 | }
35 |
36 | public TaskEntity queryWidthId(String taskId) {
37 | return DownloadManager.getInstance().getDaoSession().getTaskEntityDao().queryBuilder().where(TaskEntityDao.Properties.TaskId.eq(taskId)).unique();
38 | }
39 |
40 | public List queryAll() {
41 | return DownloadManager.getInstance().getDaoSession().getTaskEntityDao().loadAll();
42 | }
43 |
44 | public void update(TaskEntity entity) {
45 | TaskEntityDao taskEntityDao = DownloadManager.getInstance().getDaoSession().getTaskEntityDao();
46 | if(taskEntityDao.hasKey(entity)) {
47 | taskEntityDao.update(entity);
48 | }
49 | }
50 |
51 | public void delete(TaskEntity entity) {
52 | DownloadManager.getInstance().getDaoSession().delete(entity);
53 | }
54 |
55 | }
56 |
--------------------------------------------------------------------------------
/library/src/main/java/com/yuan/library/dmanager/download/DownloadManager.java:
--------------------------------------------------------------------------------
1 | package com.yuan.library.dmanager.download;
2 |
3 | import android.content.Context;
4 | import android.database.sqlite.SQLiteDatabase;
5 | import android.support.annotation.NonNull;
6 | import android.text.TextUtils;
7 | import android.util.Log;
8 |
9 | import com.yuan.library.BuildConfig;
10 | import com.yuan.library.dmanager.db.DaoManager;
11 | import com.yuan.library.dmanager.utils.Constants;
12 |
13 | import java.io.File;
14 | import java.util.HashMap;
15 | import java.util.List;
16 | import java.util.Map;
17 | import java.util.concurrent.LinkedBlockingQueue;
18 | import java.util.concurrent.ThreadPoolExecutor;
19 | import java.util.concurrent.TimeUnit;
20 |
21 | import okhttp3.OkHttpClient;
22 |
23 | public class DownloadManager {
24 |
25 | // manager instance
26 | private static DownloadManager mInstance;
27 |
28 | // quess
29 | private LinkedBlockingQueue mQueue;
30 |
31 | // ok http
32 | private OkHttpClient mClient;
33 |
34 | // ThreadPoolExecutor
35 | private ThreadPoolExecutor mExecutor;
36 |
37 | // the thread count
38 | private int mThreadCount = 1;
39 |
40 | // task list
41 | private Map mCurrentTaskList;
42 |
43 | // greenDao seesion
44 | private DaoSession mDaoSession;
45 |
46 | private DownloadManager() {
47 |
48 | }
49 |
50 | public static synchronized DownloadManager getInstance() {
51 | if (mInstance == null) {
52 | mInstance = new DownloadManager();
53 | }
54 | return mInstance;
55 | }
56 |
57 | /**
58 | * @param context Application
59 | */
60 | public void init(@NonNull Context context) {
61 | init(context, getAppropriateThreadCount());
62 | }
63 |
64 | /**
65 | * @param context Application
66 | * @param threadCount the max download count
67 | */
68 | public void init(@NonNull Context context, int threadCount) {
69 | init(context, threadCount, getOkHttpClient());
70 | }
71 |
72 | /**
73 | * @param context Application
74 | * @param threadCount the max download count
75 | * @param client okhttp client
76 | */
77 |
78 | public void init(@NonNull Context context, int threadCount, @NonNull OkHttpClient client) {
79 | setupDatabase(context);
80 |
81 | recoveryTaskState();
82 | mClient = client;
83 | mThreadCount = threadCount < 1 ? 1 : threadCount <= Constants.MAX_THREAD_COUNT ? threadCount : Constants.MAX_THREAD_COUNT;
84 | mExecutor = new ThreadPoolExecutor(mThreadCount, mThreadCount, 20, TimeUnit.MILLISECONDS, new LinkedBlockingQueue());
85 | mCurrentTaskList = new HashMap<>();
86 | mQueue = (LinkedBlockingQueue) mExecutor.getQueue();
87 |
88 |
89 | }
90 |
91 | private void setupDatabase(Context context) {
92 | DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, "download.db", null);
93 | SQLiteDatabase db = helper.getWritableDatabase();
94 | DaoMaster master = new DaoMaster(db);
95 | mDaoSession = master.newSession();
96 | }
97 |
98 | public DaoSession getDaoSession() {
99 | return mDaoSession;
100 | }
101 |
102 |
103 | /**
104 | * generate default client
105 | */
106 | private OkHttpClient getOkHttpClient() {
107 | return new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS).build();
108 | }
109 |
110 |
111 | /**
112 | * @return generate the appropriate thread count.
113 | */
114 | private int getAppropriateThreadCount() {
115 | return Runtime.getRuntime().availableProcessors() * 2 + 1;
116 | }
117 |
118 | /**
119 | * add task
120 | */
121 | public void addTask(@NonNull DownloadTask task) {
122 |
123 | TaskEntity taskEntity = task.getTaskEntity();
124 |
125 | if (taskEntity != null && taskEntity.getTaskStatus() != TaskStatus.TASK_STATUS_DOWNLOADING) {
126 | task.setClient(mClient);
127 | mCurrentTaskList.put(taskEntity.getTaskId(), task);
128 | if (!mQueue.contains(task)) {
129 | mExecutor.execute(task);
130 | }
131 |
132 | if (mExecutor.getTaskCount() > mThreadCount) {
133 | task.queue();
134 | }
135 | }
136 | }
137 |
138 | /**
139 | * pauseTask task
140 | */
141 | public void pauseTask(@NonNull DownloadTask task) {
142 | if (mQueue.contains(task)) {
143 | mQueue.remove(task);
144 | }
145 | task.pause();
146 | }
147 |
148 | /**
149 | * resumeTask task
150 | */
151 | public void resumeTask(@NonNull DownloadTask task) {
152 | addTask(task);
153 | }
154 |
155 |
156 | /**
157 | * cancel task
158 | */
159 | public void cancelTask(DownloadTask task) {
160 | if(task == null) return;
161 | TaskEntity taskEntity = task.getTaskEntity();
162 | if (taskEntity != null) {
163 | if(task.getTaskEntity().getTaskStatus() == TaskStatus.TASK_STATUS_DOWNLOADING){
164 | pauseTask(task);
165 | mExecutor.remove(task);
166 | }
167 |
168 | if (mQueue.contains(task)) {
169 | mQueue.remove(task);
170 | }
171 | mCurrentTaskList.remove(taskEntity.getTaskId());
172 | task.cancel();
173 | if (!TextUtils.isEmpty(taskEntity.getFilePath()) && !TextUtils.isEmpty(taskEntity.getFileName())) {
174 | File temp = new File(taskEntity.getFilePath(), taskEntity.getFileName());
175 | if (temp.exists()) {
176 | if (temp.delete()) {
177 | if (BuildConfig.DEBUG) Log.d("DownloadManager", "delete temp file!");
178 | }
179 | }
180 | }
181 | }
182 | }
183 |
184 | /**
185 | * @return task
186 | */
187 | public DownloadTask getTask(String id) {
188 | DownloadTask currTask = mCurrentTaskList.get(id);
189 | if (currTask == null) {
190 | TaskEntity entity = DaoManager.instance().queryWidthId(id);
191 | if (entity != null) {
192 | int status = entity.getTaskStatus();
193 | currTask = new DownloadTask(entity);
194 | if (status != TaskStatus.TASK_STATUS_FINISH) {
195 | mCurrentTaskList.put(id, currTask);
196 | }
197 | }
198 | }
199 | return currTask;
200 | }
201 |
202 |
203 | public boolean isPauseTask(String id) {
204 | TaskEntity entity = DaoManager.instance().queryWidthId(id);
205 | if (entity != null) {
206 | File file = new File(entity.getFilePath(), entity.getFilePath());
207 | if (file.exists()) {
208 | long totalSize = entity.getTotalSize();
209 | return totalSize > 0 && file.length() < totalSize;
210 | }
211 | }
212 | return false;
213 | }
214 |
215 | public boolean isFinishTask(String id) {
216 | TaskEntity entity = DaoManager.instance().queryWidthId(id);
217 | if (entity != null) {
218 | File file = new File(entity.getFilePath(), entity.getFileName());
219 | if (file.exists()) {
220 | return file.length() == entity.getTotalSize();
221 | }
222 | }
223 | return false;
224 | }
225 |
226 | private void recoveryTaskState() {
227 | List entities = DaoManager.instance().queryAll();
228 | for (TaskEntity entity : entities) {
229 | long completedSize = entity.getCompletedSize();
230 | long totalSize = entity.getTotalSize();
231 | if (completedSize > 0 && completedSize != totalSize && entity.getTaskStatus() != TaskStatus.TASK_STATUS_PAUSE) {
232 | entity.setTaskStatus(TaskStatus.TASK_STATUS_PAUSE);
233 | }
234 | DaoManager.instance().update(entity);
235 | }
236 | }
237 |
238 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/yuan/library/dmanager/download/DownloadTask.java:
--------------------------------------------------------------------------------
1 | package com.yuan.library.dmanager.download;
2 |
3 | import android.os.Handler;
4 | import android.os.Looper;
5 | import android.os.Message;
6 | import android.text.TextUtils;
7 | import android.util.Log;
8 |
9 | import com.yuan.library.dmanager.db.DaoManager;
10 | import com.yuan.library.dmanager.utils.FileUtils;
11 | import com.yuan.library.dmanager.utils.IOUtils;
12 |
13 | import java.io.BufferedInputStream;
14 | import java.io.File;
15 | import java.io.FileNotFoundException;
16 | import java.io.IOException;
17 | import java.io.InputStream;
18 | import java.io.RandomAccessFile;
19 | import java.net.ConnectException;
20 | import java.net.SocketTimeoutException;
21 |
22 | import okhttp3.OkHttpClient;
23 | import okhttp3.Request;
24 | import okhttp3.Response;
25 | import okhttp3.ResponseBody;
26 |
27 | /**
28 | * Created by Yuan on 27/09/2016:10:44 AM.
29 | *
30 | * Description:com.yuan.library.dmanager.download.DownloadTask
31 | */
32 |
33 | public class DownloadTask implements Runnable {
34 |
35 | private OkHttpClient mClient;
36 |
37 | private TaskEntity mTaskEntity;
38 |
39 | private DownloadTaskListener mListener;
40 |
41 | private Handler handler = new Handler(Looper.getMainLooper()) {
42 | @Override
43 | public void handleMessage(Message msg) {
44 | int code = msg.what;
45 | switch (code) {
46 | case TaskStatus.TASK_STATUS_QUEUE:
47 | mListener.onQueue(DownloadTask.this);
48 | break;
49 | case TaskStatus.TASK_STATUS_CONNECTING:
50 | mListener.onConnecting(DownloadTask.this);
51 | break;
52 | case TaskStatus.TASK_STATUS_DOWNLOADING:
53 | mListener.onStart(DownloadTask.this);
54 | break;
55 | case TaskStatus.TASK_STATUS_PAUSE:
56 | mListener.onPause(DownloadTask.this);
57 | break;
58 | case TaskStatus.TASK_STATUS_CANCEL:
59 | mListener.onCancel(DownloadTask.this);
60 | break;
61 | case TaskStatus.TASK_STATUS_REQUEST_ERROR:
62 | mListener.onError(DownloadTask.this, TaskStatus.TASK_STATUS_REQUEST_ERROR);
63 | break;
64 | case TaskStatus.TASK_STATUS_STORAGE_ERROR:
65 | mListener.onError(DownloadTask.this, TaskStatus.TASK_STATUS_STORAGE_ERROR);
66 | break;
67 | case TaskStatus.TASK_STATUS_FINISH:
68 | mListener.onFinish(DownloadTask.this);
69 | break;
70 |
71 | }
72 | }
73 | };
74 |
75 |
76 | public DownloadTask(TaskEntity taskEntity) {
77 | mTaskEntity = taskEntity;
78 | }
79 |
80 | @Override
81 | public void run() {
82 | InputStream inputStream = null;
83 | BufferedInputStream bis = null;
84 | RandomAccessFile tempFile = null;
85 |
86 | try {
87 |
88 |
89 | String fileName = TextUtils.isEmpty(mTaskEntity.getFileName()) ? FileUtils.getFileNameFromUrl(mTaskEntity.getUrl()) : mTaskEntity.getFileName();
90 | String filePath = TextUtils.isEmpty(mTaskEntity.getFilePath()) ? FileUtils.getDefaultFilePath() : mTaskEntity.getFilePath();
91 | mTaskEntity.setFileName(fileName);
92 | mTaskEntity.setFilePath(filePath);
93 | tempFile = new RandomAccessFile(new File(filePath, fileName), "rwd");
94 |
95 | mTaskEntity.setTaskStatus(TaskStatus.TASK_STATUS_CONNECTING);
96 | handler.sendEmptyMessage(TaskStatus.TASK_STATUS_CONNECTING);
97 |
98 | if (DaoManager.instance().queryWidthId(mTaskEntity.getTaskId()) != null) {
99 | DaoManager.instance().update(mTaskEntity);
100 | }
101 |
102 | long completedSize = mTaskEntity.getCompletedSize();
103 | Request request;
104 | try {
105 | request = new Request.Builder().url(mTaskEntity.getUrl()).header("RANGE", "bytes=" + completedSize + "-").build();
106 | } catch (IllegalArgumentException e) {
107 | mTaskEntity.setTaskStatus(TaskStatus.TASK_STATUS_REQUEST_ERROR);
108 | handler.sendEmptyMessage(TaskStatus.TASK_STATUS_REQUEST_ERROR);
109 | Log.d("DownloadTask", e.getMessage());
110 | return;
111 | }
112 |
113 | if (tempFile.length() == 0) {
114 | completedSize = 0;
115 | }
116 | tempFile.seek(completedSize);
117 |
118 | Response response = mClient.newCall(request).execute();
119 | if (response.isSuccessful()) {
120 | ResponseBody responseBody = response.body();
121 | if (responseBody != null) {
122 | if (DaoManager.instance().queryWidthId(mTaskEntity.getTaskId()) == null) {
123 | DaoManager.instance().insertOrReplace(mTaskEntity);
124 | mTaskEntity.setTotalSize(responseBody.contentLength());
125 | }
126 | mTaskEntity.setTaskStatus(TaskStatus.TASK_STATUS_DOWNLOADING);
127 |
128 | double updateSize = mTaskEntity.getTotalSize() / 100;
129 | inputStream = responseBody.byteStream();
130 | bis = new BufferedInputStream(inputStream);
131 | byte[] buffer = new byte[1024];
132 | int length;
133 | int buffOffset = 0;
134 | while ((length = bis.read(buffer)) > 0 && mTaskEntity.getTaskStatus() != TaskStatus.TASK_STATUS_CANCEL && mTaskEntity.getTaskStatus() != TaskStatus.TASK_STATUS_PAUSE) {
135 | tempFile.write(buffer, 0, length);
136 | completedSize += length;
137 | buffOffset += length;
138 | mTaskEntity.setCompletedSize(completedSize);
139 | // 避免一直调用数据库
140 | if (buffOffset >= updateSize) {
141 | buffOffset = 0;
142 | DaoManager.instance().update(mTaskEntity);
143 | handler.sendEmptyMessage(TaskStatus.TASK_STATUS_DOWNLOADING);
144 | }
145 |
146 | if (completedSize == mTaskEntity.getTotalSize()) {
147 | handler.sendEmptyMessage(TaskStatus.TASK_STATUS_DOWNLOADING);
148 | mTaskEntity.setTaskStatus(TaskStatus.TASK_STATUS_FINISH);
149 | handler.sendEmptyMessage(TaskStatus.TASK_STATUS_FINISH);
150 | DaoManager.instance().update(mTaskEntity);
151 | }
152 | }
153 | }
154 | } else {
155 | mTaskEntity.setTaskStatus(TaskStatus.TASK_STATUS_REQUEST_ERROR);
156 | handler.sendEmptyMessage(TaskStatus.TASK_STATUS_REQUEST_ERROR);
157 | }
158 |
159 |
160 | } catch (FileNotFoundException e) {
161 | mTaskEntity.setTaskStatus(TaskStatus.TASK_STATUS_STORAGE_ERROR);
162 | handler.sendEmptyMessage(TaskStatus.TASK_STATUS_STORAGE_ERROR);
163 | } catch (SocketTimeoutException | ConnectException e) {
164 | mTaskEntity.setTaskStatus(TaskStatus.TASK_STATUS_REQUEST_ERROR);
165 | handler.sendEmptyMessage(TaskStatus.TASK_STATUS_REQUEST_ERROR);
166 | } catch (IOException e) {
167 | e.printStackTrace();
168 | } finally {
169 | IOUtils.close(bis, inputStream, tempFile);
170 | }
171 | }
172 |
173 | public TaskEntity getTaskEntity() {
174 | return mTaskEntity;
175 | }
176 |
177 | void pause() {
178 | mTaskEntity.setTaskStatus(TaskStatus.TASK_STATUS_PAUSE);
179 | DaoManager.instance().update(mTaskEntity);
180 | handler.sendEmptyMessage(TaskStatus.TASK_STATUS_PAUSE);
181 | }
182 |
183 | void queue() {
184 | mTaskEntity.setTaskStatus(TaskStatus.TASK_STATUS_QUEUE);
185 | handler.sendEmptyMessage(TaskStatus.TASK_STATUS_QUEUE);
186 | }
187 |
188 | void cancel() {
189 | mTaskEntity.setTaskStatus(TaskStatus.TASK_STATUS_CANCEL);
190 | DaoManager.instance().delete(mTaskEntity);
191 | handler.sendEmptyMessage(TaskStatus.TASK_STATUS_CANCEL);
192 | }
193 |
194 | void setClient(OkHttpClient mClient) {
195 | this.mClient = mClient;
196 | }
197 |
198 | public void setListener(DownloadTaskListener listener) {
199 | mListener = listener;
200 | }
201 |
202 |
203 | }
204 |
--------------------------------------------------------------------------------
/library/src/main/java/com/yuan/library/dmanager/download/DownloadTaskListener.java:
--------------------------------------------------------------------------------
1 | package com.yuan.library.dmanager.download;
2 |
3 | import java.io.File;
4 |
5 | /**
6 | * Created by Yuan on 27/09/2016:10:47 AM.
7 | *
8 | * Description:com.yuan.library.dmanager.download.DownloadTaskListener
9 | */
10 |
11 | public interface DownloadTaskListener {
12 |
13 |
14 | void onQueue(DownloadTask downloadTask);
15 |
16 | /**
17 | * connecting
18 | */
19 | void onConnecting(DownloadTask downloadTask);
20 |
21 | /**
22 | * downloading
23 | */
24 | void onStart(DownloadTask downloadTask);
25 |
26 | /**
27 | * pauseTask
28 | */
29 | void onPause(DownloadTask downloadTask);
30 |
31 | /**
32 | * cancel
33 | */
34 | void onCancel(DownloadTask downloadTask);
35 |
36 | /**
37 | * success
38 | */
39 | void onFinish(DownloadTask downloadTask);
40 |
41 | /**
42 | * failure
43 | */
44 | void onError(DownloadTask downloadTask, int code);
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/library/src/main/java/com/yuan/library/dmanager/download/TaskEntity.java:
--------------------------------------------------------------------------------
1 | package com.yuan.library.dmanager.download;
2 |
3 | import android.text.TextUtils;
4 |
5 | import org.greenrobot.greendao.annotation.Entity;
6 | import org.greenrobot.greendao.annotation.Generated;
7 | import org.greenrobot.greendao.annotation.Id;
8 | import org.greenrobot.greendao.annotation.Property;
9 |
10 | /**
11 | * Created by Yuan on 8/17/16.
12 | *
13 | * download status
14 | */
15 |
16 | @Entity(nameInDb = "download_status")
17 | public class TaskEntity {
18 |
19 | /**
20 | * + "id INTEGER PRIMARY KEY autoincrement,"
21 | + "taskId TEXT,"
22 | + "totalSize LONG,"
23 | + "completedSize LONG,"
24 | + "url TEXT,"
25 | + "filePath TEXT,"
26 | + "fileName TEXT,"
27 | + "taskStatus INTEGER" + ");";
28 | */
29 | @Id(autoincrement = true)
30 | private Long id;
31 | @Property
32 | private String taskId;
33 | @Property
34 | private long totalSize;
35 | @Property
36 | private long completedSize;
37 | @Property
38 | private String url;
39 | @Property
40 | private String filePath;
41 | @Property
42 | private String fileName;
43 | @Property
44 | private int taskStatus;
45 |
46 |
47 | private TaskEntity(Builder builder) {
48 | this.taskId = builder.taskId;
49 | this.totalSize = builder.totalSize;
50 | this.completedSize = builder.completedSize;
51 | this.url = builder.url;
52 | this.filePath = builder.filePath;
53 | this.fileName = builder.fileName;
54 | this.taskStatus = builder.taskStatus;
55 | }
56 |
57 | @Generated(hash = 1689179221)
58 | public TaskEntity(Long id, String taskId, long totalSize, long completedSize, String url,
59 | String filePath, String fileName, int taskStatus) {
60 | this.id = id;
61 | this.taskId = taskId;
62 | this.totalSize = totalSize;
63 | this.completedSize = completedSize;
64 | this.url = url;
65 | this.filePath = filePath;
66 | this.fileName = fileName;
67 | this.taskStatus = taskStatus;
68 | }
69 |
70 | @Generated(hash = 397975341)
71 | public TaskEntity() {
72 | }
73 |
74 | public String getTaskId() {
75 | taskId = TextUtils.isEmpty(taskId) ? String.valueOf(url.hashCode()) : taskId;
76 | return taskId;
77 | }
78 |
79 | public long getTotalSize() {
80 | return totalSize;
81 | }
82 |
83 | public long getCompletedSize() {
84 | return completedSize;
85 | }
86 |
87 | public void setCompletedSize(Long completedSize) {
88 | this.completedSize = completedSize;
89 | }
90 |
91 | public String getUrl() {
92 | return url;
93 | }
94 |
95 | public String getFilePath() {
96 | return filePath;
97 | }
98 |
99 | public String getFileName() {
100 | return fileName;
101 | }
102 |
103 | public int getTaskStatus() {
104 | return taskStatus;
105 | }
106 |
107 | public void setTaskId(String taskId) {
108 | this.taskId = taskId;
109 | }
110 |
111 | public void setTotalSize(long totalSize) {
112 | this.totalSize = totalSize;
113 | }
114 |
115 | public void setCompletedSize(long completedSize) {
116 | this.completedSize = completedSize;
117 | }
118 |
119 | public void setUrl(String url) {
120 | this.url = url;
121 | }
122 |
123 | public void setFilePath(String filePath) {
124 | this.filePath = filePath;
125 | }
126 |
127 | public void setFileName(String fileName) {
128 | this.fileName = fileName;
129 | }
130 |
131 | public void setTaskStatus(int taskStatus) {
132 | this.taskStatus = taskStatus;
133 | }
134 |
135 | public void setTaskStatus(Integer taskStatus) {
136 | this.taskStatus = taskStatus;
137 | }
138 |
139 | public static class Builder {
140 | // file id
141 | private String taskId;
142 | // file length
143 | private long totalSize;
144 | // file complete length
145 | private long completedSize;
146 | // file url
147 | private String url;
148 | // file save path
149 | private String filePath;
150 | // file name
151 | private String fileName;
152 | // file download status
153 | private int taskStatus;
154 |
155 | public Builder downloadId(String taskId) {
156 | this.taskId = taskId;
157 | return this;
158 | }
159 |
160 | public Builder totalSize(long totalSize) {
161 | this.totalSize = totalSize;
162 | return this;
163 | }
164 |
165 | public Builder completedSize(long completedSize) {
166 | this.completedSize = completedSize;
167 | return this;
168 | }
169 |
170 | public Builder url(String url) {
171 | this.url = url;
172 | return this;
173 | }
174 |
175 | public Builder filePath(String saveDirPath) {
176 | this.filePath = saveDirPath;
177 | return this;
178 | }
179 |
180 | public Builder fileName(String fileName) {
181 | this.fileName = fileName;
182 | return this;
183 | }
184 |
185 | public Builder downloadStatus(int downloadStatus) {
186 | this.taskStatus = downloadStatus;
187 | return this;
188 | }
189 |
190 | public TaskEntity build() {
191 | return new TaskEntity(this);
192 | }
193 |
194 | }
195 |
196 | @Override
197 | public String toString() {
198 | return "TaskEntity{" +
199 | "taskId='" + taskId + '\'' +
200 | ", totalSize=" + totalSize +
201 | ", completedSize=" + completedSize +
202 | ", url='" + url + '\'' +
203 | ", filePath='" + filePath + '\'' +
204 | ", fileName='" + fileName + '\'' +
205 | ", taskStatus=" + taskStatus +
206 | '}';
207 | }
208 |
209 | public Long getId() {
210 | return this.id;
211 | }
212 |
213 | public void setId(Long id) {
214 | this.id = id;
215 | }
216 | }
217 |
--------------------------------------------------------------------------------
/library/src/main/java/com/yuan/library/dmanager/download/TaskStatus.java:
--------------------------------------------------------------------------------
1 | package com.yuan.library.dmanager.download;
2 |
3 | /**
4 | * Created by Yuan on 27/09/2016:10:48 AM.
5 | *
6 | * Description:com.yuan.library.dmanager.download.TaskStatus
7 | */
8 |
9 | public class TaskStatus {
10 |
11 | /**
12 | * init download
13 | */
14 | public static final int TASK_STATUS_INIT = 0;
15 |
16 | /**
17 | * queue download
18 | */
19 | public static final int TASK_STATUS_QUEUE = TASK_STATUS_INIT + 1;
20 |
21 | /**
22 | * resume download
23 | */
24 | public static final int TASK_STATUS_CONNECTING = TASK_STATUS_QUEUE + 1;
25 |
26 | /**
27 | * start download
28 | */
29 | public static final int TASK_STATUS_DOWNLOADING = TASK_STATUS_CONNECTING + 1;
30 |
31 | /**
32 | * cancel download
33 | */
34 | public static final int TASK_STATUS_CANCEL = TASK_STATUS_DOWNLOADING + 1;
35 |
36 | /**
37 | * pause download
38 | */
39 | public static final int TASK_STATUS_PAUSE = TASK_STATUS_CANCEL + 1;
40 |
41 | /**
42 | * request error
43 | */
44 | public static final int TASK_STATUS_REQUEST_ERROR = TASK_STATUS_PAUSE + 1;
45 |
46 | /**
47 | * storage error
48 | */
49 | public static final int TASK_STATUS_STORAGE_ERROR = TASK_STATUS_REQUEST_ERROR + 1;
50 |
51 | /**
52 | * finish download
53 | */
54 | public static final int TASK_STATUS_FINISH = TASK_STATUS_STORAGE_ERROR + 1;
55 | }
56 |
--------------------------------------------------------------------------------
/library/src/main/java/com/yuan/library/dmanager/utils/Constants.java:
--------------------------------------------------------------------------------
1 | package com.yuan.library.dmanager.utils;
2 |
3 | /**
4 | * Created by yuan on 09/12/2016.
5 | */
6 |
7 | public class Constants {
8 | public static final int MAX_THREAD_COUNT = 15;
9 | }
10 |
--------------------------------------------------------------------------------
/library/src/main/java/com/yuan/library/dmanager/utils/FileUtils.java:
--------------------------------------------------------------------------------
1 | package com.yuan.library.dmanager.utils;
2 |
3 | import android.os.Environment;
4 | import android.text.TextUtils;
5 | import android.util.Log;
6 |
7 | import com.yuan.library.BuildConfig;
8 |
9 | import java.io.File;
10 |
11 | /**
12 | * Created by yuan on 07/12/2016.
13 | */
14 |
15 | public class FileUtils {
16 |
17 | /**
18 | * 从url获取 如果url为空,则文件名为当前时间毫秒值
19 | *
20 | * @param url download file url
21 | * @return file name
22 | */
23 | public static String getFileNameFromUrl(String url) {
24 | if (!TextUtils.isEmpty(url)) {
25 | return url.substring(url.lastIndexOf("/") + 1);
26 | }
27 | return System.currentTimeMillis() + "";
28 | }
29 |
30 | public static String getDefaultFilePath() {
31 | String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/okhttp/download/";
32 | File file = new File(filePath);
33 | if (!file.exists()) {
34 | boolean createDir = file.mkdirs();
35 | if (createDir) {
36 | if (BuildConfig.DEBUG) Log.d("DownloadTask", "create file dir success");
37 | }
38 | }
39 | return filePath;
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/library/src/main/java/com/yuan/library/dmanager/utils/IOUtils.java:
--------------------------------------------------------------------------------
1 | package com.yuan.library.dmanager.utils;
2 |
3 | import java.io.Closeable;
4 | import java.io.IOException;
5 |
6 | /**
7 | * Created by yuan on 07/12/2016.
8 | */
9 |
10 | public class IOUtils {
11 |
12 | /**
13 | * 关闭流
14 | * @param closeables io
15 | */
16 | public static void close(Closeable... closeables) {
17 | for (Closeable io : closeables) {
18 | if (io != null) {
19 | try {
20 | io.close();
21 | } catch (IOException e) {
22 | e.printStackTrace();
23 | }
24 | }
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/library/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Library
3 |
4 |
--------------------------------------------------------------------------------
/library/src/test/java/com/yuan/library/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.yuan.library;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() throws Exception {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/local.properties:
--------------------------------------------------------------------------------
1 | ## This file is automatically generated by Android Studio.
2 | # Do not modify this file -- YOUR CHANGES WILL BE ERASED!
3 | #
4 | # This file must *NOT* be checked into Version Control Systems,
5 | # as it contains information specific to your local configuration.
6 | #
7 | # Location of the SDK. This is only used by Gradle.
8 | # For customization when using a Version Control System, please read the
9 | # header note.
10 | #Wed Nov 30 10:58:41 CST 2016
11 | sdk.dir=/Users/yuan/Work/adt-bundle-mac/sdk
12 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':library'
2 |
--------------------------------------------------------------------------------