├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ ├── colors.xml
│ │ │ │ └── styles.xml
│ │ │ ├── mipmap-hdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-mdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-anydpi-v26
│ │ │ │ ├── ic_launcher.xml
│ │ │ │ └── ic_launcher_round.xml
│ │ │ ├── layout
│ │ │ │ ├── activity_main.xml
│ │ │ │ └── activity_download.xml
│ │ │ ├── drawable
│ │ │ │ ├── progressbar_bg.xml
│ │ │ │ └── ic_launcher_background.xml
│ │ │ └── drawable-v24
│ │ │ │ └── ic_launcher_foreground.xml
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── yang
│ │ │ │ └── download
│ │ │ │ ├── MainActivity.kt
│ │ │ │ ├── download
│ │ │ │ ├── DownloadResponseHandler.java
│ │ │ │ ├── DownloadInfo.java
│ │ │ │ ├── ResponseProgressBody.java
│ │ │ │ ├── SpTool.java
│ │ │ │ └── DownloadManager.java
│ │ │ │ └── DownLoadActivity.java
│ │ └── AndroidManifest.xml
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── yang
│ │ │ └── download
│ │ │ └── ExampleUnitTest.kt
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── yang
│ │ └── download
│ │ └── ExampleInstrumentedTest.kt
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .idea
├── caches
│ └── build_file_checksums.ser
├── vcs.xml
├── modules.xml
├── runConfigurations.xml
├── gradle.xml
├── codeStyles
│ └── Project.xml
└── misc.xml
├── .gitignore
├── gradle.properties
├── gradlew.bat
├── README.md
└── gradlew
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | DownLoadManager
3 |
4 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cleveryang/DownLoadManager/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/.idea/caches/build_file_checksums.ser:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cleveryang/DownLoadManager/HEAD/.idea/caches/build_file_checksums.ser
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cleveryang/DownLoadManager/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cleveryang/DownLoadManager/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cleveryang/DownLoadManager/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cleveryang/DownLoadManager/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cleveryang/DownLoadManager/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cleveryang/DownLoadManager/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cleveryang/DownLoadManager/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cleveryang/DownLoadManager/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cleveryang/DownLoadManager/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cleveryang/DownLoadManager/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/workspace.xml
5 | /.idea/libraries
6 | .DS_Store
7 | /build
8 | /captures
9 | .externalNativeBuild
10 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Fri Sep 14 14:28:14 CST 2018
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-4.4-all.zip
7 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/app/src/main/java/com/yang/download/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.yang.download
2 |
3 | import android.support.v7.app.AppCompatActivity
4 | import android.os.Bundle
5 |
6 | class MainActivity : AppCompatActivity() {
7 |
8 | override fun onCreate(savedInstanceState: Bundle?) {
9 | super.onCreate(savedInstanceState)
10 | setContentView(R.layout.activity_main)
11 |
12 | DownLoadActivity.startActivity(this)
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/test/java/com/yang/download/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.yang.download
2 |
3 | import org.junit.Test
4 |
5 | import org.junit.Assert.*
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * See [testing documentation](http://d.android.com/tools/testing).
11 | */
12 | class ExampleUnitTest {
13 | @Test
14 | fun addition_isCorrect() {
15 | assertEquals(4, 2 + 2)
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/app/src/main/java/com/yang/download/download/DownloadResponseHandler.java:
--------------------------------------------------------------------------------
1 | package com.yang.download.download;
2 |
3 | import java.io.File;
4 |
5 | /**
6 | * 下载回调
7 | * Created by yang on 18/6/29.
8 | */
9 | public abstract class DownloadResponseHandler {
10 |
11 | public abstract void onProgress(long currentBytes, long totalBytes);
12 | public abstract void onFinish(File download_file);
13 | public abstract void onPause(DownloadInfo downloadInfo);
14 | public abstract void onCancle(DownloadInfo downloadInfo);
15 | public abstract void onFailure(String error_msg);
16 | }
17 |
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
11 |
12 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/yang/download/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.yang.download
2 |
3 | import android.support.test.InstrumentationRegistry
4 | import android.support.test.runner.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getTargetContext()
22 | assertEquals("com.yang.download", appContext.packageName)
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/progressbar_bg.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | -
5 |
6 |
7 |
10 |
11 |
12 |
13 |
14 | -
15 |
16 |
17 |
18 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | apply plugin: 'kotlin-android'
4 |
5 | apply plugin: 'kotlin-android-extensions'
6 |
7 | android {
8 | compileSdkVersion 26
9 | defaultConfig {
10 | applicationId "com.yang.download"
11 | minSdkVersion 14
12 | targetSdkVersion 26
13 | versionCode 1
14 | versionName "1.0"
15 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
16 | }
17 | buildTypes {
18 | release {
19 | minifyEnabled false
20 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
21 | }
22 | }
23 | }
24 |
25 | dependencies {
26 | implementation fileTree(dir: 'libs', include: ['*.jar'])
27 | implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
28 | implementation 'com.android.support:appcompat-v7:26.1.0'
29 | implementation 'com.android.support.constraint:constraint-layout:1.1.2'
30 | testImplementation 'junit:junit:4.12'
31 | androidTestImplementation 'com.android.support.test:runner:1.0.2'
32 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
33 |
34 | //OKHttp
35 | implementation 'com.squareup.okhttp3:okhttp:3.10.0'
36 | //BindView
37 | implementation 'com.jakewharton:butterknife:8.8.1'
38 | annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
39 | //eventbus
40 | implementation 'org.greenrobot:eventbus:3.1.1'
41 | //fastjson
42 | implementation 'com.alibaba:fastjson:1.2.34'
43 | }
44 |
--------------------------------------------------------------------------------
/app/src/main/java/com/yang/download/download/DownloadInfo.java:
--------------------------------------------------------------------------------
1 | package com.yang.download.download;
2 |
3 | import java.io.Serializable;
4 |
5 | /**
6 | * Created by yang on 2018/6/21.
7 | * 下载信息
8 | */
9 |
10 | public class DownloadInfo implements Serializable{
11 | private String url;//下载路径
12 | private String targetUrl;//存储路径
13 | private long total;//总大小
14 | private long progress;//当前进度
15 | private String fileName;//名称
16 | private int downloadState;//下载状态
17 |
18 | public DownloadInfo(String url) {
19 | this.url = url;
20 | }
21 |
22 | public String getUrl() {
23 | return url;
24 | }
25 |
26 | public String getFileName() {
27 | return fileName;
28 | }
29 |
30 | public void setFileName(String fileName) {
31 | this.fileName = fileName;
32 | }
33 |
34 | public long getTotal() {
35 | return total;
36 | }
37 |
38 | public void setTotal(long total) {
39 | this.total = total;
40 | }
41 |
42 | public long getProgress() {
43 | return progress;
44 | }
45 |
46 | public void setProgress(long progress) {
47 | this.progress = progress;
48 | }
49 |
50 | public String getTargetUrl() {
51 | return targetUrl;
52 | }
53 |
54 | public void setTargetUrl(String targetUrl) {
55 | this.targetUrl = targetUrl;
56 | }
57 |
58 | public void setDownloadState(int downloadState) {
59 | this.downloadState = downloadState;
60 | }
61 |
62 | public int getDownloadState() {
63 | return downloadState;
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
33 |
34 |
35 |
--------------------------------------------------------------------------------
/.idea/codeStyles/Project.xml:
--------------------------------------------------------------------------------
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 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # DownloadManager
2 | ## Android下载管理器
3 |
4 | 1、可实现下载、暂停、取消、完成、失败、队列等待等状态的监听
5 |
6 | 2、可断点续传
7 |
8 | 3、基于okhttp的下载管理器,可实现单个页面的进度回调,也可实现所有下载进度的监听.
9 |
10 | 4、可获取下载队列里和已完成下载的所有任务
11 |
12 | 5、可设置最大同时下载线程数
13 |
14 | ## 使用方法
15 | 下载方式有三种:
16 |
17 | /**
18 | * 添加下载任务
19 | *
20 | * @param url 下载请求的网址
21 | * @param targetUrl 下载保存的位置
22 | */
23 | DownLoadManager.getInstance(this).download(String url, String targetUrl);
24 |
25 | /**
26 | * 添加下载任务
27 | *
28 | * @param url 下载请求的网址
29 | * @param targetUrl 下载保存的位置
30 | * @param downloadResponseHandler 用来回调的接口
31 | */
32 | DownLoadManager.getInstance(this).download(String url, String targetUrl, final DownloadResponseHandler downloadResponseHandler);
33 |
34 | /**
35 | * 添加下载任务
36 | *
37 | * @param downloadInfo 下载类
38 | * @param downloadResponseHandler 用来回调的接口
39 | */
40 | DownLoadManager.getInstance(this).download(DownloadInfo downloadInfo, final DownloadResponseHandler downloadResponseHandler)
41 |
42 | 监听下载进度
43 |
44 | 单个任务监听
45 |
46 | DownloadResponseHandler回调
47 |
48 | 全局监听(eventbus实现,也可用广播等)
49 |
50 | @Subscribe(threadMode = ThreadMode.BACKGROUND)
51 | public void onMessageEvent(DownloadInfo info){
52 | //返回info对象(这是在子线程)
53 | }
54 |
55 | 取消下载
56 |
57 | DownLoadManager.getInstance(this).cancel(url);
58 |
59 | 取消全部下载
60 |
61 | DownLoadManager.getInstance(this).cancelAll();
62 |
63 |
64 | 暂停下载
65 |
66 | DownLoadManager.getInstance(this).pause(url);
67 |
68 | 暂停全部下载
69 |
70 | DownLoadManager.getInstance(this).pauseAll();
71 |
72 | 设置同时下载请求数(默认为1)
73 |
74 | DownLoadManager.getInstance(this).setMaxRequests(1);
75 |
76 | 得到下载队列(等待中,下载中和暂停的任务)
77 |
78 | DownloadManager.getInstance(this).getDownloadInfos();
79 |
80 | 得到已完成队列(不校验文件是否存在或完整,如用户手动删除了源文件)
81 |
82 | DownloadManager.getInstance(this).getCompleteInfos();
83 |
84 | ## 说明介绍
85 |
86 | DownloadInfo类
87 |
88 | private String url;//下载路径
89 | private String targetUrl;//存储路径
90 | private long total;//总大小
91 | private long progress;//当前进度
92 | private String fileName;//名称
93 | private int downloadState;//下载状态
94 |
95 | 各个下载状态
96 |
97 | public static final int DOWNLOAD_STATE_WAITING = 0x00;//等待
98 | public static final int DOWNLOAD_STATE_DOWNLOADING = 0x01;//下载中
99 | public static final int DOWNLOAD_STATE_PAUSE = 0x02;//暂停
100 | public static final int DOWNLOAD_STATE_CANCLE = 0x03;//取消
101 | public static final int DOWNLOAD_STATE_FINISH = 0x04;//完成
102 | public static final int DOWNLOAD_STATE_FAIL = 0x05;//失败
103 | public static final int DOWNLOAD_STATE_RESTART = 0x06;//重新下载
104 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_download.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
14 |
22 |
27 |
32 |
33 |
37 |
45 |
50 |
55 |
56 |
60 |
68 |
73 |
78 |
79 |
80 |
83 |
86 |
87 |
91 |
92 |
93 |
94 |
--------------------------------------------------------------------------------
/app/src/main/java/com/yang/download/download/ResponseProgressBody.java:
--------------------------------------------------------------------------------
1 | package com.yang.download.download;
2 |
3 | import android.content.Context;
4 | import android.os.Handler;
5 | import android.os.Looper;
6 |
7 | import org.greenrobot.eventbus.EventBus;
8 |
9 | import java.io.IOException;
10 | import java.util.Map;
11 |
12 | import okhttp3.MediaType;
13 | import okhttp3.ResponseBody;
14 | import okio.Buffer;
15 | import okio.BufferedSource;
16 | import okio.ForwardingSource;
17 | import okio.Okio;
18 | import okio.Source;
19 |
20 |
21 | /**
22 | * 重写responsebody 设置下载进度监听
23 | * Created by yang on 18/6/29.
24 | */
25 | public class ResponseProgressBody extends ResponseBody {
26 |
27 | private ResponseBody mResponseBody;
28 | private DownloadResponseHandler mDownloadResponseHandler;
29 | private BufferedSource bufferedSource;
30 | private DownloadInfo info;
31 | private long progress;//开始前已下载进度
32 | private Context mContext;
33 | private Map downloadInfos;
34 | private Handler handler;
35 |
36 | public ResponseProgressBody(Context context, ResponseBody responseBody, DownloadResponseHandler downloadResponseHandler, DownloadInfo info) {
37 | this.mResponseBody = responseBody;
38 | this.mDownloadResponseHandler = downloadResponseHandler;
39 | this.info = info;
40 | this.mContext = context;
41 | progress = info.getProgress();
42 | downloadInfos = SpTool.getMap(mContext, DownloadManager.DOWNLOAD_MAPS);
43 | if (info.getTotal() <= 0) {
44 | info.setTotal(mResponseBody.contentLength());
45 | if (downloadInfos != null) {
46 | downloadInfos.put(info.getUrl(), info);
47 | SpTool.putMap(mContext, DownloadManager.DOWNLOAD_MAPS, downloadInfos);
48 | }
49 | }
50 |
51 | handler = new Handler(Looper.getMainLooper());
52 | }
53 |
54 | @Override
55 | public MediaType contentType() {
56 | return mResponseBody.contentType();
57 | }
58 |
59 | @Override
60 | public long contentLength() {
61 | return mResponseBody.contentLength();
62 | }
63 |
64 | @Override
65 | public BufferedSource source() {
66 | if (bufferedSource == null) {
67 | bufferedSource = Okio.buffer(source(mResponseBody.source()));
68 | }
69 | return bufferedSource;
70 | }
71 |
72 | private Source source(Source source) {
73 |
74 | return new ForwardingSource(source) {
75 |
76 | long totalBytesRead;
77 |
78 | @Override
79 | public long read(Buffer sink, long byteCount) throws IOException {
80 | long bytesRead = super.read(sink, byteCount);
81 | totalBytesRead += ((bytesRead != -1) ? bytesRead : 0);
82 | if (mDownloadResponseHandler != null) {
83 | info.setProgress(totalBytesRead + progress);
84 | // mDownloadResponseHandler.onProgress(totalBytesRead+(info!=null?info.getProgress():0), info!=null?info.getProgress()+mResponseBody.contentLength():mResponseBody.contentLength());
85 | handler.post(new Runnable() {
86 | @Override
87 | public void run() {
88 | mDownloadResponseHandler.onProgress(info.getProgress(), info.getTotal());
89 | }
90 | });
91 | info.setDownloadState(DownloadManager.DOWNLOAD_STATE_DOWNLOADING);
92 |
93 | if (downloadInfos != null) {
94 | downloadInfos.put(info.getUrl(), info);
95 | SpTool.putMap(mContext, DownloadManager.DOWNLOAD_MAPS, downloadInfos);
96 | }
97 | EventBus.getDefault().post(info);
98 | }
99 | return bytesRead;
100 | }
101 | };
102 | }
103 | }
104 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
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 | Android
36 |
37 |
38 | Bitwise operation issuesJava
39 |
40 |
41 | C/C++
42 |
43 |
44 | Class structureJava
45 |
46 |
47 | Code style issuesJava
48 |
49 |
50 | CorrectnessLintAndroid
51 |
52 |
53 | Data flow analysisC/C++
54 |
55 |
56 | Finalization issuesJava
57 |
58 |
59 | Groovy
60 |
61 |
62 | IconsUsabilityLintAndroid
63 |
64 |
65 | Initialization issuesJava
66 |
67 |
68 | Internationalization issuesJava
69 |
70 |
71 | J2ME issuesJava
72 |
73 |
74 | JUnit issuesJava
75 |
76 |
77 | Java
78 |
79 |
80 | Java 5Java language level migration aidsJava
81 |
82 |
83 | Java 7Java language level migration aidsJava
84 |
85 |
86 | Java language level migration aidsJava
87 |
88 |
89 | Kotlin
90 |
91 |
92 | LintAndroid
93 |
94 |
95 | Logging issuesJava
96 |
97 |
98 | Memory issuesJava
99 |
100 |
101 | MessagesCorrectnessLintAndroid
102 |
103 |
104 | Numeric issuesJava
105 |
106 |
107 | OtherGroovy
108 |
109 |
110 | Performance issuesJava
111 |
112 |
113 | Potentially confusing code constructsGroovy
114 |
115 |
116 | Probable bugsGroovy
117 |
118 |
119 | Probable bugsJava
120 |
121 |
122 | Serialization issuesJava
123 |
124 |
125 | Style issuesKotlin
126 |
127 |
128 | Threading issuesGroovy
129 |
130 |
131 | Threading issuesJava
132 |
133 |
134 | Type checksC/C++
135 |
136 |
137 | UsabilityLintAndroid
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 |
151 |
152 |
153 | 1.8
154 |
155 |
156 |
157 |
158 |
159 |
160 |
161 |
162 |
163 |
164 |
165 |
166 |
167 |
168 |
169 |
170 |
171 |
172 |
173 |
174 |
175 |
176 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/app/src/main/java/com/yang/download/DownLoadActivity.java:
--------------------------------------------------------------------------------
1 | package com.yang.download;
2 |
3 | import android.content.Context;
4 | import android.content.Intent;
5 | import android.os.Bundle;
6 | import android.os.Environment;
7 | import android.support.annotation.Nullable;
8 | import android.support.v7.app.AppCompatActivity;
9 | import android.util.Log;
10 | import android.widget.ProgressBar;
11 | import android.widget.TextView;
12 |
13 | import com.yang.download.download.DownloadManager;
14 | import com.yang.download.download.DownloadInfo;
15 | import com.yang.download.download.DownloadResponseHandler;
16 |
17 | import org.greenrobot.eventbus.EventBus;
18 | import org.greenrobot.eventbus.Subscribe;
19 | import org.greenrobot.eventbus.ThreadMode;
20 |
21 | import java.io.File;
22 |
23 | import butterknife.BindView;
24 | import butterknife.ButterKnife;
25 | import butterknife.OnClick;
26 | import butterknife.Unbinder;
27 |
28 | /**
29 | * Created by yang on 2018/3/27.
30 | */
31 |
32 | public class DownLoadActivity extends AppCompatActivity {
33 |
34 | @BindView(R.id.main_progress1)
35 | ProgressBar progressBar1;
36 |
37 | @BindView(R.id.main_progress2)
38 | ProgressBar progressBar2;
39 |
40 | @BindView(R.id.main_progress3)
41 | ProgressBar progressBar3;
42 |
43 | @BindView(R.id.txt)
44 | TextView txt;
45 |
46 | protected Unbinder mUnbinder;
47 |
48 | private String url1 = "https://raw.githubusercontent.com/scwang90/SmartRefreshLayout/master/art/app-debug.apk";
49 | private String url2 = "https://download.superlearn.com/app/toefl.apk";
50 | private String url3 = "https://leguimg.qcloud.com/files/LEGUMAC.zip";
51 |
52 |
53 | public static void startActivity(Context ctx) {
54 | Intent intent = new Intent(ctx, DownLoadActivity.class);
55 | ctx.startActivity(intent);
56 | }
57 |
58 | @Override
59 | public void onCreate(@Nullable Bundle savedInstanceState) {
60 | super.onCreate(savedInstanceState);
61 | setContentView(R.layout.activity_download);
62 | mUnbinder = ButterKnife.bind(this);
63 | DownloadManager.getInstance(this).setMaxRequests(2);
64 | }
65 |
66 | @Override
67 | protected void onStart() {
68 | super.onStart();
69 | EventBus.getDefault().register(this);
70 | }
71 |
72 | @Override
73 | protected void onStop() {
74 | super.onStop();
75 | EventBus.getDefault().unregister(this);
76 | }
77 |
78 | @Subscribe(threadMode = ThreadMode.BACKGROUND)
79 | public void onMessageEvent(DownloadInfo info){
80 | txt.setText(txt.getText().toString()+"\n"+info.getUrl()+"---progress:"+info.getProgress()+"---total:"+info.getTotal());
81 | }
82 |
83 | @OnClick(R.id.main_btn_down1)
84 | void onDown1() {
85 | DownloadManager.getInstance(this).download(url1, getDiskFileDir(this) + "/app.apk", new DownloadResponseHandler() {
86 | @Override
87 | public void onFinish(File download_file) {
88 |
89 | }
90 |
91 | @Override
92 | public void onProgress(long currentBytes, long totalBytes) {
93 | Log.e("DownLoadManager", currentBytes + "----" + totalBytes);
94 | progressBar1.setMax((int) totalBytes);
95 | progressBar1.setProgress((int) currentBytes);
96 | }
97 |
98 | @Override
99 | public void onFailure(String error_msg) {
100 |
101 | }
102 |
103 | @Override
104 | public void onPause(DownloadInfo info) {
105 |
106 | }
107 |
108 | @Override
109 | public void onCancle(DownloadInfo info) {
110 |
111 | }
112 | });
113 | }
114 |
115 | @OnClick(R.id.main_btn_down2)
116 | void onDown2() {
117 | DownloadManager.getInstance(this).download(url2, getDiskFileDir(this) + "/toefl.apk", new DownloadResponseHandler() {
118 | @Override
119 | public void onFinish(File download_file) {
120 |
121 | }
122 |
123 | @Override
124 | public void onProgress(long currentBytes, long totalBytes) {
125 | Log.e("DownLoadManager", currentBytes + "----" + totalBytes);
126 | progressBar2.setMax((int) totalBytes);
127 | progressBar2.setProgress((int) currentBytes);
128 | }
129 |
130 | @Override
131 | public void onFailure(String error_msg) {
132 |
133 | }
134 |
135 | @Override
136 | public void onPause(DownloadInfo info) {
137 |
138 | }
139 |
140 | @Override
141 | public void onCancle(DownloadInfo info) {
142 |
143 | }
144 | });
145 | }
146 |
147 | @OnClick(R.id.main_btn_down3)
148 | void onDown3() {
149 | DownloadManager.getInstance(this).download(url3, getDiskFileDir(this) + "/le.zip", new DownloadResponseHandler() {
150 | @Override
151 | public void onFinish(File download_file) {
152 |
153 | }
154 |
155 | @Override
156 | public void onProgress(long currentBytes, long totalBytes) {
157 | Log.e("DownLoadManager", currentBytes + "----" + totalBytes);
158 | progressBar3.setMax((int) totalBytes);
159 | progressBar3.setProgress((int) currentBytes);
160 | }
161 |
162 | @Override
163 | public void onFailure(String error_msg) {
164 |
165 | }
166 |
167 | @Override
168 | public void onPause(DownloadInfo info) {
169 |
170 | }
171 |
172 | @Override
173 | public void onCancle(DownloadInfo info) {
174 |
175 | }
176 | });
177 | }
178 |
179 | @OnClick(R.id.main_btn_cancel1)
180 | void onCancle1() {
181 | DownloadManager.getInstance(this).pause(url1);
182 | }
183 |
184 | @OnClick(R.id.main_btn_cancel2)
185 | void onCancle2() {
186 | DownloadManager.getInstance(this).pause(url2);
187 | }
188 |
189 | @OnClick(R.id.main_btn_cancel3)
190 | void onCancle3() {
191 | DownloadManager.getInstance(this).pause(url3);
192 | }
193 |
194 | @Override
195 | protected void onDestroy() {
196 | super.onDestroy();
197 | if (null != mUnbinder) mUnbinder.unbind();
198 | }
199 |
200 | /**
201 | * 获取缓存文件目录
202 | *
203 | * @param context
204 | * @return
205 | */
206 | public static String getDiskFileDir(Context context) {
207 | String cachePath = null;
208 | if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable()) {
209 | cachePath = context.getExternalFilesDir(null).getPath();
210 | } else {
211 | cachePath = context.getFilesDir().getPath();
212 | }
213 | return cachePath;
214 | }
215 | }
216 |
--------------------------------------------------------------------------------
/app/src/main/java/com/yang/download/download/SpTool.java:
--------------------------------------------------------------------------------
1 | package com.yang.download.download;
2 |
3 | import android.content.Context;
4 | import android.content.SharedPreferences;
5 | import android.text.TextUtils;
6 | import android.util.Base64;
7 |
8 | import java.io.ByteArrayInputStream;
9 | import java.io.ByteArrayOutputStream;
10 | import java.io.IOException;
11 | import java.io.ObjectInputStream;
12 | import java.io.ObjectOutputStream;
13 | import java.io.Serializable;
14 | import java.util.List;
15 | import java.util.Map;
16 |
17 | /**
18 | * Created by yang on 2018/7/10.
19 | */
20 |
21 | public class SpTool {
22 |
23 | private static SharedPreferences sp;
24 |
25 | private static SharedPreferences getSp(Context context) {
26 | if (sp == null) {
27 | sp = context.getSharedPreferences("SpTool", Context.MODE_PRIVATE);
28 | }
29 | return sp;
30 | }
31 |
32 |
33 | /**
34 | * 存入字符串
35 | *
36 | * @param context 上下文
37 | * @param key 字符串的键
38 | * @param value 字符串的值
39 | */
40 | public static void putString(Context context, String key, String value) {
41 | SharedPreferences preferences = getSp(context);
42 | //存入数据
43 | SharedPreferences.Editor editor = preferences.edit();
44 | editor.putString(key, value);
45 | editor.commit();
46 | }
47 |
48 | /**
49 | * 获取字符串
50 | *
51 | * @param context 上下文
52 | * @param key 字符串的键
53 | * @return 得到的字符串
54 | */
55 | public static String getString(Context context, String key) {
56 | SharedPreferences preferences = getSp(context);
57 | return preferences.getString(key, "");
58 | }
59 |
60 | /**
61 | * 获取字符串
62 | *
63 | * @param context 上下文
64 | * @param key 字符串的键
65 | * @param value 字符串的默认值
66 | * @return 得到的字符串
67 | */
68 | public static String getString(Context context, String key, String value) {
69 | SharedPreferences preferences = getSp(context);
70 | return preferences.getString(key, value);
71 | }
72 |
73 | /**
74 | * 保存布尔值
75 | *
76 | * @param context 上下文
77 | * @param key 键
78 | * @param value 值
79 | */
80 | public static void putBoolean(Context context, String key, boolean value) {
81 | SharedPreferences sp = getSp(context);
82 | SharedPreferences.Editor editor = sp.edit();
83 | editor.putBoolean(key, value);
84 | editor.commit();
85 | }
86 |
87 | /**
88 | * 获取布尔值
89 | *
90 | * @param context 上下文
91 | * @param key 键
92 | * @param defValue 默认值
93 | * @return 返回保存的值
94 | */
95 | public static boolean getBoolean(Context context, String key, boolean defValue) {
96 | SharedPreferences sp = getSp(context);
97 | return sp.getBoolean(key, defValue);
98 | }
99 |
100 | /**
101 | * 保存long值
102 | *
103 | * @param context 上下文
104 | * @param key 键
105 | * @param value 值
106 | */
107 | public static void putLong(Context context, String key, long value) {
108 | SharedPreferences sp = getSp(context);
109 | SharedPreferences.Editor editor = sp.edit();
110 | editor.putLong(key, value);
111 | editor.commit();
112 | }
113 |
114 | /**
115 | * 获取long值
116 | *
117 | * @param context 上下文
118 | * @param key 键
119 | * @param defValue 默认值
120 | * @return 保存的值
121 | */
122 | public static long getLong(Context context, String key, long defValue) {
123 | SharedPreferences sp = getSp(context);
124 | return sp.getLong(key, defValue);
125 | }
126 |
127 | /**
128 | * 保存int值
129 | *
130 | * @param context 上下文
131 | * @param key 键
132 | * @param value 值
133 | */
134 | public static void putInt(Context context, String key, int value) {
135 | SharedPreferences sp = getSp(context);
136 | SharedPreferences.Editor editor = sp.edit();
137 | editor.putInt(key, value);
138 | editor.commit();
139 | }
140 |
141 | /**
142 | * 获取long值
143 | *
144 | * @param context 上下文
145 | * @param key 键
146 | * @param defValue 默认值
147 | * @return 保存的值
148 | */
149 | public static int getInt(Context context, String key, int defValue) {
150 | SharedPreferences sp = getSp(context);
151 | return sp.getInt(key, defValue);
152 | }
153 |
154 | /**
155 | * 保存对象
156 | *
157 | * @param context 上下文
158 | * @param key 键
159 | * @param obj 要保存的对象(Serializable的子类)
160 | * @param 泛型定义
161 | */
162 | public static void putObject(Context context, String key, T obj) {
163 | try {
164 | put(context, key, obj);
165 | } catch (Exception e) {
166 | e.printStackTrace();
167 | }
168 | }
169 |
170 | /**
171 | * 获取对象
172 | *
173 | * @param context 上下文
174 | * @param key 键
175 | * @param 指定泛型
176 | * @return 泛型对象
177 | */
178 | public static T getObject(Context context, String key) {
179 | try {
180 | return (T) get(context, key);
181 | } catch (Exception e) {
182 | e.printStackTrace();
183 | }
184 | return null;
185 | }
186 |
187 | /**
188 | * 存储List集合
189 | *
190 | * @param context 上下文
191 | * @param key 存储的键
192 | * @param list 存储的集合
193 | */
194 | public static void putList(Context context, String key, List extends Serializable> list) {
195 | try {
196 | put(context, key, list);
197 | } catch (Exception e) {
198 | e.printStackTrace();
199 | }
200 | }
201 |
202 | /**
203 | * 获取List集合
204 | *
205 | * @param context 上下文
206 | * @param key 键
207 | * @param 指定泛型
208 | * @return List集合
209 | */
210 | public static List getList(Context context, String key) {
211 | try {
212 | return (List) get(context, key);
213 | } catch (Exception e) {
214 | e.printStackTrace();
215 | }
216 | return null;
217 | }
218 |
219 | /**
220 | * 存储Map集合
221 | *
222 | * @param context 上下文
223 | * @param key 键
224 | * @param map 存储的集合
225 | * @param 指定Map的键
226 | * @param 指定Map的值
227 | */
228 | public static void putMap(Context context,
229 | String key, Map map) {
230 | try {
231 | put(context, key, map);
232 | } catch (Exception e) {
233 | e.printStackTrace();
234 | }
235 | }
236 |
237 | public static Map getMap(Context context,
238 | String key) {
239 | try {
240 | return (Map) get(context, key);
241 | } catch (Exception e) {
242 | e.printStackTrace();
243 | }
244 | return null;
245 | }
246 |
247 | /**
248 | * 存储对象
249 | */
250 | private static void put(Context context, String key, Object obj)
251 | throws IOException {
252 | if (obj == null) {//判断对象是否为空
253 | return;
254 | }
255 | ByteArrayOutputStream baos = new ByteArrayOutputStream();
256 | ObjectOutputStream oos = null;
257 | oos = new ObjectOutputStream(baos);
258 | oos.writeObject(obj);
259 | // 将对象放到OutputStream中
260 | // 将对象转换成byte数组,并将其进行base64编码
261 | String objectStr = new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT));
262 | baos.close();
263 | oos.close();
264 |
265 | putString(context, key, objectStr);
266 | }
267 |
268 | /**
269 | * 获取对象
270 | */
271 | private static Object get(Context context, String key)
272 | throws IOException, ClassNotFoundException {
273 | String wordBase64 = getString(context, key);
274 | // 将base64格式字符串还原成byte数组
275 | if (TextUtils.isEmpty(wordBase64)) { //不可少,否则在下面会报java.io.StreamCorruptedException
276 | return null;
277 | }
278 | byte[] objBytes = Base64.decode(wordBase64.getBytes(), Base64.DEFAULT);
279 | ByteArrayInputStream bais = new ByteArrayInputStream(objBytes);
280 | ObjectInputStream ois = new ObjectInputStream(bais);
281 | // 将byte数组转换成product对象
282 | Object obj = ois.readObject();
283 | bais.close();
284 | ois.close();
285 | return obj;
286 | }
287 | }
288 |
--------------------------------------------------------------------------------
/app/src/main/java/com/yang/download/download/DownloadManager.java:
--------------------------------------------------------------------------------
1 | package com.yang.download.download;
2 |
3 | import android.content.Context;
4 | import android.os.Handler;
5 | import android.text.TextUtils;
6 | import android.util.Log;
7 |
8 | import org.greenrobot.eventbus.EventBus;
9 |
10 | import java.io.File;
11 | import java.io.FileOutputStream;
12 | import java.io.IOException;
13 | import java.io.InputStream;
14 | import java.util.HashMap;
15 | import java.util.Map;
16 | import java.util.concurrent.atomic.AtomicReference;
17 |
18 | import okhttp3.Call;
19 | import okhttp3.Callback;
20 | import okhttp3.Interceptor;
21 | import okhttp3.OkHttpClient;
22 | import okhttp3.Request;
23 | import okhttp3.Response;
24 |
25 | /**
26 | * Created by yang on 2018/6/29.
27 | * 下载管理器
28 | */
29 |
30 | public class DownloadManager {
31 |
32 | // 下载状态
33 | public static final int DOWNLOAD_STATE_WAITING = 0x00;//等待
34 | public static final int DOWNLOAD_STATE_DOWNLOADING = 0x01;//下载中
35 | public static final int DOWNLOAD_STATE_PAUSE = 0x02;//暂停
36 | public static final int DOWNLOAD_STATE_CANCLE = 0x03;//取消
37 | public static final int DOWNLOAD_STATE_FINISH = 0x04;//完成
38 | public static final int DOWNLOAD_STATE_FAIL = 0x05;//失败
39 | public static final int DOWNLOAD_STATE_RESTART = 0x06;//重新下载
40 |
41 | private static final AtomicReference INSTANCE = new AtomicReference<>();
42 | private OkHttpClient mClient;//OKHttpClient;
43 | private Context mContext;
44 | private int maxRequests = 1;
45 | private Map downloadInfos = new HashMap<>();
46 | private Map completeInfos = new HashMap<>();
47 | public static final String DOWNLOAD_MAPS = "DOWNLOAD_MAPS";//下载队列的
48 | public static final String COMPLETE_MAPS = "COMPLETE_MAPS";//已完成的
49 |
50 |
51 | //获得一个单例类
52 | public static DownloadManager getInstance(Context context) {
53 | for (; ; ) {
54 | DownloadManager current = INSTANCE.get();
55 | if (current != null) {
56 | return current;
57 | }
58 | current = new DownloadManager(context);
59 | if (INSTANCE.compareAndSet(null, current)) {
60 | return current;
61 | }
62 | }
63 | }
64 |
65 | private DownloadManager(Context context) {
66 | mClient = new OkHttpClient();
67 | mClient.dispatcher().setMaxRequests(maxRequests);
68 | mContext = context;
69 | downloadInfos = SpTool.getMap(mContext, DOWNLOAD_MAPS);
70 | if (downloadInfos == null)
71 | downloadInfos = new HashMap<>();
72 | completeInfos = SpTool.getMap(mContext, COMPLETE_MAPS);
73 | if (completeInfos == null)
74 | completeInfos = new HashMap<>();
75 | }
76 |
77 | /**
78 | * 设置最大请求数
79 | *
80 | * @param maxRequests
81 | */
82 | public void setMaxRequests(int maxRequests) {
83 | this.maxRequests = maxRequests;
84 | if (mClient != null)
85 | mClient.dispatcher().setMaxRequests(maxRequests);
86 | }
87 |
88 | /**
89 | * 得到下载队列
90 | *
91 | * @return
92 | */
93 | public Map getDownloadInfos() {
94 | return downloadInfos != null ? downloadInfos : new HashMap();
95 | }
96 |
97 | /**
98 | * 得到已完成队列
99 | *
100 | * @return
101 | */
102 | public Map getCompleteInfos() {
103 | return completeInfos != null ? completeInfos : new HashMap();
104 | }
105 |
106 | /**
107 | * 取消全部下载
108 | *
109 | * @param url
110 | */
111 | public void cancelAll(String url) {
112 | if (mClient != null) {
113 | for (Call call : mClient.dispatcher().queuedCalls()) {
114 | cancel(call.request().tag().toString());
115 | }
116 | for (Call call : mClient.dispatcher().runningCalls()) {
117 | cancel(call.request().tag().toString());
118 | }
119 | }
120 | }
121 |
122 | /**
123 | * 取消下载
124 | *
125 | * @param url
126 | */
127 | public void cancel(String url) {
128 | if (mClient != null) {
129 | for (Call call : mClient.dispatcher().queuedCalls()) {
130 | if (call.request().tag().equals(url))
131 | call.cancel();
132 | }
133 | for (Call call : mClient.dispatcher().runningCalls()) {
134 | if (call.request().tag().equals(url))
135 | call.cancel();
136 | }
137 | }
138 | if (downloadInfos.get(url) != null) {
139 | DownloadInfo cancleInfo = downloadInfos.get(url);
140 | cancleInfo.setDownloadState(DOWNLOAD_STATE_CANCLE);
141 | downloadInfos.remove(cancleInfo.getUrl());
142 | SpTool.putMap(mContext, DOWNLOAD_MAPS, downloadInfos);
143 | File file = new File(cancleInfo.getTargetUrl());
144 | if (file.exists())
145 | file.delete();
146 | }
147 | }
148 |
149 | /**
150 | * 暂停全部下载
151 | */
152 | public void pauseAll() {
153 | if (mClient != null) {
154 | for (Call call : mClient.dispatcher().queuedCalls()) {
155 | pause(call.request().tag().toString());
156 | }
157 | for (Call call : mClient.dispatcher().runningCalls()) {
158 | pause(call.request().tag().toString());
159 | }
160 | }
161 |
162 | }
163 |
164 | /**
165 | * 暂停下载
166 | *
167 | * @param url
168 | */
169 | public void pause(String url) {
170 | if (mClient != null) {
171 | for (Call call : mClient.dispatcher().queuedCalls()) {
172 | if (call.request().tag().equals(url))
173 | call.cancel();
174 | }
175 | for (Call call : mClient.dispatcher().runningCalls()) {
176 | if (call.request().tag().equals(url))
177 | call.cancel();
178 | }
179 | }
180 | if (downloadInfos.get(url) != null) {
181 | DownloadInfo pauseInfo = downloadInfos.get(url);
182 | pauseInfo.setDownloadState(DOWNLOAD_STATE_PAUSE);
183 | downloadInfos.put(pauseInfo.getUrl(), pauseInfo);
184 | SpTool.putMap(mContext, DOWNLOAD_MAPS, downloadInfos);
185 | }
186 | }
187 |
188 | /**
189 | * 添加下载任务
190 | *
191 | * @param url 下载请求的网址
192 | * @param targetUrl 下载保存的位置
193 | */
194 | public void download(String url, String targetUrl) {
195 | download(url, targetUrl, new DownloadResponseHandler() {
196 | @Override
197 | public void onFinish(File download_file) {
198 |
199 | }
200 |
201 | @Override
202 | public void onProgress(long currentBytes, long totalBytes) {
203 |
204 | }
205 |
206 | @Override
207 | public void onFailure(String error_msg) {
208 |
209 | }
210 |
211 | @Override
212 | public void onCancle(DownloadInfo info) {
213 |
214 | }
215 |
216 | @Override
217 | public void onPause(DownloadInfo info) {
218 |
219 | }
220 | });
221 | }
222 |
223 | /**
224 | * 添加下载任务
225 | *
226 | * @param url 下载请求的网址
227 | * @param targetUrl 下载保存的位置
228 | * @param downloadResponseHandler 用来回调的接口
229 | */
230 | public void download(String url, String targetUrl, final DownloadResponseHandler downloadResponseHandler) {
231 | DownloadInfo downloadInfo = new DownloadInfo(url);
232 | downloadInfo.setTargetUrl(targetUrl);
233 | download(downloadInfo, downloadResponseHandler);
234 | }
235 |
236 | /**
237 | * 添加下载任务
238 | */
239 | public void download(DownloadInfo downloadInfo) {
240 | download(downloadInfo, new DownloadResponseHandler() {
241 | @Override
242 | public void onProgress(long currentBytes, long totalBytes) {
243 |
244 | }
245 |
246 | @Override
247 | public void onFinish(File download_file) {
248 |
249 | }
250 |
251 | @Override
252 | public void onPause(DownloadInfo downloadInfo) {
253 |
254 | }
255 |
256 | @Override
257 | public void onCancle(DownloadInfo downloadInfo) {
258 |
259 | }
260 |
261 | @Override
262 | public void onFailure(String error_msg) {
263 |
264 | }
265 | });
266 | }
267 |
268 | /**
269 | * 添加下载任务
270 | *
271 | * @param downloadInfo 下载类
272 | * @param downloadResponseHandler 用来回调的接口
273 | */
274 | public void download(DownloadInfo downloadInfo, final DownloadResponseHandler downloadResponseHandler) {
275 |
276 | if (mClient != null) {//包含下载url,不做处理
277 | for (Call call : mClient.dispatcher().queuedCalls()) {
278 | if (call.request().tag().equals(downloadInfo.getUrl()))
279 | return;
280 | }
281 | for (Call call : mClient.dispatcher().runningCalls()) {
282 | if (call.request().tag().equals(downloadInfo.getUrl()))
283 | return;
284 | }
285 | }
286 | DownloadInfo info;
287 | Request request;
288 | if (downloadInfos.get(downloadInfo.getUrl()) != null) {//在下载队列中
289 | info = downloadInfos.get(downloadInfo.getUrl());
290 | File file = new File(info.getTargetUrl());
291 | boolean isNormal = true;
292 | if (file.exists()) {
293 | //找到了文件,代表已经下载过,则获取其长度
294 | info.setProgress(file.length());
295 | if (info.getProgress() >= info.getTotal()) {
296 | isNormal = false;
297 | file.delete();
298 | info.setProgress(0);
299 | info.setTotal(0);
300 | } else
301 | downloadResponseHandler.onProgress(info.getProgress(), info.getTotal());
302 | }
303 | info.setDownloadState(DOWNLOAD_STATE_WAITING);
304 | downloadInfos.put(info.getUrl(), info);
305 | SpTool.putMap(mContext, DOWNLOAD_MAPS, downloadInfos);
306 | EventBus.getDefault().post(info);
307 | if (isNormal)
308 | request = new Request.Builder()
309 | .addHeader("RANGE", "bytes=" + info.getProgress() + "-" + info.getTotal())
310 | .url(info.getUrl())
311 | .tag(info.getUrl())
312 | .build();
313 | else request = new Request.Builder()
314 | .url(info.getUrl())
315 | .tag(info.getUrl())
316 | .build();
317 | } else {//添加新任务
318 | info = downloadInfo;
319 | info.setDownloadState(DOWNLOAD_STATE_WAITING);
320 | if (TextUtils.isEmpty(downloadInfo.getFileName())) {
321 | String fileName = downloadInfo.getTargetUrl().substring(downloadInfo.getTargetUrl().lastIndexOf("/"));
322 | if (fileName.startsWith("/") && fileName.length() > 1)
323 | fileName = fileName.substring(1);
324 | info.setFileName(fileName);
325 | }
326 | downloadInfos.put(info.getUrl(), info);
327 | SpTool.putMap(mContext, DOWNLOAD_MAPS, downloadInfos);
328 | EventBus.getDefault().post(info);
329 | request = new Request.Builder()
330 | .url(info.getUrl())
331 | .tag(info.getUrl())
332 | .build();
333 | }
334 |
335 | final DownloadInfo finalInfo = info;
336 | Call call = mClient.newBuilder()
337 | .addNetworkInterceptor(new Interceptor() { //设置拦截器
338 | @Override
339 | public Response intercept(Chain chain) throws IOException {
340 | Response originalResponse = chain.proceed(chain.request());
341 | return originalResponse.newBuilder()
342 | .body(new ResponseProgressBody(mContext, originalResponse.body(), downloadResponseHandler, finalInfo))
343 | .build();
344 | }
345 | })
346 | .build()
347 | .newCall(request);
348 | call.enqueue(new MyDownloadCallback(new Handler(), downloadResponseHandler, finalInfo));
349 | }
350 |
351 | //下载回调
352 | private class MyDownloadCallback implements Callback {
353 |
354 | private Handler mHandler;
355 | private DownloadResponseHandler mDownloadResponseHandler;
356 | private DownloadInfo info;
357 | private String targetUrl;
358 |
359 | public MyDownloadCallback(Handler handler, DownloadResponseHandler downloadResponseHandler, DownloadInfo info) {
360 | mHandler = handler;
361 | mDownloadResponseHandler = downloadResponseHandler;
362 | this.targetUrl = info.getTargetUrl();
363 | this.info = info;
364 | }
365 |
366 | @Override
367 | public void onFailure(Call call, final IOException e) {
368 | Log.e("onFailure", e.getMessage());
369 |
370 | mHandler.post(new Runnable() {
371 | @Override
372 | public void run() {
373 | mDownloadResponseHandler.onFailure(e.toString());
374 | info.setDownloadState(DOWNLOAD_STATE_FAIL);
375 | downloadInfos.put(info.getUrl(), info);
376 | SpTool.putMap(mContext, DOWNLOAD_MAPS, downloadInfos);
377 | EventBus.getDefault().post(info);
378 | }
379 | });
380 | }
381 |
382 | @Override
383 | public void onResponse(Call call, final Response response) throws IOException {
384 | if (response.isSuccessful()) {
385 | File file = null;
386 | try {
387 | file = saveFile(response, targetUrl);
388 | final File newFile = file;
389 | mHandler.post(new Runnable() {
390 | @Override
391 | public void run() {
392 | mDownloadResponseHandler.onFinish(newFile);
393 |
394 | info.setDownloadState(DOWNLOAD_STATE_FINISH);
395 | downloadInfos.remove(info.getUrl());
396 | completeInfos.put(info.getUrl(), info);
397 | SpTool.putMap(mContext, DOWNLOAD_MAPS, downloadInfos);
398 | SpTool.putMap(mContext, COMPLETE_MAPS, completeInfos);
399 | EventBus.getDefault().post(info);
400 | }
401 | });
402 | } catch (final Exception e) {
403 | Log.e("onResponse fail", e.getMessage());
404 |
405 | mHandler.post(new Runnable() {
406 | @Override
407 | public void run() {
408 | switch (info.getDownloadState()) {
409 | case DOWNLOAD_STATE_CANCLE:
410 |
411 | Log.e("download cancle.", response.code() + "");
412 | mDownloadResponseHandler.onCancle(info);
413 | break;
414 | case DOWNLOAD_STATE_PAUSE:
415 | Log.e("download pause.", response.code() + "");
416 | mDownloadResponseHandler.onPause(info);
417 | break;
418 | default:
419 | Log.e("onResponse fail status", response.code() + "");
420 | mDownloadResponseHandler.onFailure("onResponse saveFile fail." + e.toString());
421 | info.setDownloadState(DOWNLOAD_STATE_FAIL);
422 | downloadInfos.put(info.getUrl(), info);
423 | SpTool.putMap(mContext, DOWNLOAD_MAPS, downloadInfos);
424 | break;
425 | }
426 |
427 | EventBus.getDefault().post(info);
428 | }
429 | });
430 | }
431 |
432 | } else {
433 | Log.e("onResponse fail status", response.code() + "");
434 |
435 | mHandler.post(new Runnable() {
436 | @Override
437 | public void run() {
438 | mDownloadResponseHandler.onFailure("fail status=" + response.code());
439 | info.setDownloadState(DOWNLOAD_STATE_FAIL);
440 | downloadInfos.put(info.getUrl(), info);
441 | SpTool.putMap(mContext, DOWNLOAD_MAPS, downloadInfos);
442 | EventBus.getDefault().post(info);
443 | }
444 | });
445 | }
446 | }
447 | }
448 |
449 | //保存文件
450 | private File saveFile(Response response, String targetUrl) throws IOException {
451 | File file = new File(targetUrl);
452 | InputStream is = null;
453 | FileOutputStream fileOutputStream = null;
454 | try {
455 | is = response.body().byteStream();
456 | fileOutputStream = new FileOutputStream(file, true);
457 | byte[] buffer = new byte[2048];//缓冲数组2kB
458 | int len;
459 | while ((len = is.read(buffer)) != -1) {
460 | fileOutputStream.write(buffer, 0, len);
461 | }
462 | fileOutputStream.flush();
463 | return file;
464 | } finally {
465 | //关闭IO流
466 | try {
467 | if (is != null) is.close();
468 | } catch (IOException e) {
469 | }
470 | try {
471 | if (fileOutputStream != null) fileOutputStream.close();
472 | } catch (IOException ignored) {
473 | }
474 | }
475 | }
476 | }
477 |
--------------------------------------------------------------------------------