├── app
├── .gitignore
├── src
│ └── main
│ │ ├── res
│ │ ├── 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
│ │ ├── values
│ │ │ ├── strings.xml
│ │ │ ├── colors.xml
│ │ │ └── styles.xml
│ │ ├── mipmap-anydpi-v26
│ │ │ ├── ic_launcher.xml
│ │ │ └── ic_launcher_round.xml
│ │ ├── layout
│ │ │ └── activity_main.xml
│ │ ├── drawable-v24
│ │ │ └── ic_launcher_foreground.xml
│ │ └── drawable
│ │ │ └── ic_launcher_background.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ └── com
│ │ └── znb
│ │ └── okdown
│ │ └── MainActivity.kt
├── proguard-rules.pro
└── build.gradle
├── okdown
├── consumer-rules.pro
├── .gitignore
├── src
│ └── main
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ └── com
│ │ └── ok
│ │ └── down
│ │ └── DownLoadHttpUtils.kt
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── Android Emulator - Pixel_2_API_29_5554 2020-05-13 23-32-12.gif
├── gradle.properties
├── gradlew.bat
├── README.md
└── gradlew
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/okdown/consumer-rules.pro:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/okdown/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 | /test
3 | *.iml
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name='OkDown'
2 | include ':app'
3 | include ':okdown'
4 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taishuhongye/OkDown/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taishuhongye/OkDown/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taishuhongye/OkDown/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/okdown/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taishuhongye/OkDown/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taishuhongye/OkDown/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taishuhongye/OkDown/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taishuhongye/OkDown/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/taishuhongye/OkDown/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/taishuhongye/OkDown/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/taishuhongye/OkDown/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/taishuhongye/OkDown/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | .idea
4 | /local.properties
5 | .DS_Store
6 | /build
7 | /captures
8 | .externalNativeBuild
9 | .cxx
10 | app/libs/
11 | */test
12 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | OkDown
3 | Hello okDown!
4 |
5 |
--------------------------------------------------------------------------------
/Android Emulator - Pixel_2_API_29_5554 2020-05-13 23-32-12.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taishuhongye/OkDown/HEAD/Android Emulator - Pixel_2_API_29_5554 2020-05-13 23-32-12.gif
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #6200EE
4 | #3700B3
5 | #03DAC5
6 |
7 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Tue May 12 16:31:56 CST 2020
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-5.6.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 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/okdown/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 |
9 |
10 |
15 |
16 |
17 |
25 |
26 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 | apply plugin: 'kotlin-android'
3 | apply plugin: 'kotlin-android-extensions'
4 |
5 | android {
6 | compileSdkVersion 29
7 | buildToolsVersion "29.0.3"
8 |
9 | defaultConfig {
10 | applicationId "com.nb.okdown"
11 | minSdkVersion 19
12 | targetSdkVersion 29
13 | versionCode 1
14 | versionName "1.0"
15 |
16 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
17 | }
18 |
19 | buildTypes {
20 | release {
21 | minifyEnabled false
22 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
23 | }
24 | }
25 |
26 | }
27 |
28 | dependencies {
29 | implementation fileTree(dir: 'libs', include: ['*.jar'])
30 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
31 | implementation 'androidx.appcompat:appcompat:1.1.0'
32 | implementation 'androidx.core:core-ktx:1.2.0'
33 | implementation project(':okdown')
34 | }
--------------------------------------------------------------------------------
/okdown/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'kotlin-android'
3 | apply plugin: 'kotlin-android-extensions'
4 |
5 | android {
6 | compileSdkVersion 29
7 | buildToolsVersion "29.0.3"
8 |
9 | defaultConfig {
10 | minSdkVersion 19
11 | targetSdkVersion 29
12 | versionCode 1
13 | versionName "1.0"
14 |
15 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
16 | consumerProguardFiles 'consumer-rules.pro'
17 | }
18 |
19 | buildTypes {
20 | release {
21 | minifyEnabled false
22 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
23 | }
24 | }
25 |
26 | }
27 |
28 | dependencies {
29 | implementation fileTree(dir: 'libs', include: ['*.jar'])
30 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
31 | implementation 'androidx.appcompat:appcompat:1.1.0'
32 | implementation 'androidx.core:core-ktx:1.2.0'
33 | implementation("com.squareup.okhttp3:okhttp:4.6.0")
34 | }
35 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
16 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx1536m
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app's APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Automatically convert third-party libraries to use AndroidX
19 | android.enableJetifier=true
20 | # Kotlin code style for this project: "official" or "obsolete":
21 | kotlin.code.style=official
22 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/app/src/main/java/com/znb/okdown/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.znb.okdown
2 |
3 | import androidx.appcompat.app.AppCompatActivity
4 | import android.os.Bundle
5 | import android.util.Log
6 | import com.ok.down.DownLoadHttpUtils
7 | import kotlinx.android.synthetic.main.activity_main.*
8 |
9 | class MainActivity : AppCompatActivity() {
10 | companion object {
11 | private val TAG = MainActivity::class.java.simpleName
12 | }
13 |
14 | override fun onCreate(savedInstanceState: Bundle?) {
15 | super.onCreate(savedInstanceState)
16 | setContentView(R.layout.activity_main)
17 |
18 | val header = HashMap()
19 | header["ua"] = "your dad"
20 | var tvTotal = ""
21 | btn_down.setOnClickListener {
22 | DownLoadHttpUtils.getInstance().setActionCallBack({
23 | tvTotal = it.toString()
24 | Log.d(TAG, "total : $it")
25 | Log.d(TAG, "Thread : ${Thread.currentThread().name}")
26 | }, {
27 | tv_progress.text = "$it/$tvTotal"
28 | Log.d(TAG, "progress : $it")
29 | Log.d(TAG, "Thread : ${Thread.currentThread().name}")
30 | }, {
31 | tv_progress.text = "$it"
32 | Log.d(TAG, "success : $it")
33 | Log.d(TAG, "Thread : ${Thread.currentThread().name}")
34 | }, {
35 | Log.d(TAG, "error : $it")
36 | Log.d(TAG, "Thread : ${Thread.currentThread().name}")
37 | })
38 | .addHeader(header)
39 | .initUrl(
40 | "https://download.sj.qq.com/upload/connAssitantDownload/upload/MobileAssistant_1.apk",
41 | null
42 | )
43 | .setFilePath(applicationContext.filesDir.absolutePath)
44 | .setFileName("app_baby.apk")//皮
45 | .down()
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/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 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
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 Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # OkDown
2 | Android 基于okhttp3 的文件下载库。
3 |
4 | **feature:**
5 | 1.调用简单,一键下载
6 | 2.支持自定义header,与其他参数详见以下注释
7 | 3.体积小,仅有一个类
8 | 4.回调自动切换主线程。
9 | 5.重复下载判断。
10 | 6.调用优雅。
11 |
12 | 一切用默认值的话,超简单且优雅:
13 | ```kotlin
14 | DownLoadHttpUtils.getInstance()
15 | .setActionCallBack({ //可选,回调函数
16 | //返回文件一共大小
17 | Log.d(TAG, "total : $it")
18 | }, {
19 | //返回当前下载进度,Long
20 | Log.d(TAG, "progress : $it")
21 | }, {
22 | //下载成功,返回文件本身。File
23 | Log.d(TAG, "success : $it")
24 | }, {
25 | //下载错误,返回错误原因
26 | Log.d(TAG, "error : $it")
27 | })
28 | .down() //必选,开始下载
29 | ```
30 |
31 | 预览 下了个应用宝。打算下抖音来着。公司那破网下抖音慢,苦恼。
32 |
33 |
34 |
35 |
36 |
37 | 还可以自定义一些参数。
38 | ```kotlin
39 | val header = HashMap()//自定义header
40 | header["ua"] = "your dad"
41 |
42 | var tvTotal = ""
43 |
44 | //以下方法,标记为必选,在down前必须调用。标记为可选,随意。
45 | DownLoadHttpUtils.getInstance()
46 | .addHeader(header) //可选,自定义header
47 | .setReadTImeOut(10L)//可选,自定义超时时间,还有writeTimeout,connectTimeout。默认均为10L
48 | .setDeleteWhenException(true)//可选,出现异常时,是否删除下载到一半的文件,默认true,删除。
49 | .initUrl(
50 | "https://download.sj.qq.com/upload/connAssitantDownload/upload/MobileAssistant_1.apk",
51 | null
52 | )//必选,下载链接和参数。参数为map类型。
53 | .setFilePath(applicationContext.filesDir.absolutePath)//必选,下载路径。
54 | .setFileName("app_baby.apk")//可选,存储的下载文件名
55 | //kotlin调用方法,优雅
56 | .setActionCallBack({ //可选,回调函数
57 | Log.d(TAG, "total : $it")
58 | Log.d(TAG, "Thread : ${Thread.currentThread().name}")
59 | }, {
60 | Log.d(TAG, "progress : $it")
61 | Log.d(TAG, "Thread : ${Thread.currentThread().name}")
62 | }, {
63 | Log.d(TAG, "success : $it")
64 | Log.d(TAG, "Thread : ${Thread.currentThread().name}")
65 | }, {
66 | Log.d(TAG, "error : $it")
67 | Log.d(TAG, "Thread : ${Thread.currentThread().name}")
68 | })
69 | .down() //必选,开始下载
70 | //非kotlin直接setDownCallBack.
71 | ```
72 |
73 |
74 | 请确保调用前,具有文件存储权限,网络请求权限。
75 |
76 |
77 |
78 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/okdown/src/main/java/com/ok/down/DownLoadHttpUtils.kt:
--------------------------------------------------------------------------------
1 | package com.ok.down
2 |
3 | import android.os.Handler
4 | import android.os.Looper
5 | import android.util.Log
6 | import okhttp3.*
7 | import okhttp3.Headers.Companion.toHeaders
8 | import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
9 | import java.io.*
10 | import java.util.concurrent.TimeUnit
11 |
12 |
13 | /**
14 | * @ClassName DownLoadHttpUtils
15 | * @Description 下载工具类
16 | * @Author 许文奇
17 | * @Date 2020/5/12 18:15
18 | * @Version 1.0
19 | */
20 | class DownLoadHttpUtils private constructor() {
21 | companion object {
22 | private const val TAG = "LoggingInterceptor"
23 | private val downLoadHttpUtils: DownLoadHttpUtils by lazy {
24 | DownLoadHttpUtils()
25 | }
26 |
27 | @JvmStatic
28 | @Synchronized
29 | fun getInstance(): DownLoadHttpUtils {
30 | return downLoadHttpUtils
31 | }
32 | }
33 |
34 | private var buffSize = 2048//建议设置为2048
35 | fun setBuffSize(size: Int): DownLoadHttpUtils {
36 | this.buffSize = size
37 | return this
38 | }
39 |
40 | private var interceptor: Interceptor? = null
41 | fun setInterceptro(interceptor: Interceptor?): DownLoadHttpUtils {
42 | this.interceptor = interceptor
43 | return this
44 | }
45 |
46 | private var readTimeOut = 10L
47 | fun setReadTImeOut(read: Long): DownLoadHttpUtils {
48 | this.readTimeOut = read
49 | return this
50 | }
51 |
52 | private var writeTimeout = 10L
53 | fun setWriteTimeOut(write: Long): DownLoadHttpUtils {
54 | this.writeTimeout = write
55 | return this
56 | }
57 |
58 | private var connectTimeout = 10L
59 | fun setConnectTimeOut(connect: Long): DownLoadHttpUtils {
60 | this.connectTimeout = connect
61 | return this
62 | }
63 |
64 | private var filePath = ""
65 | fun setFilePath(path: String): DownLoadHttpUtils {
66 | this.filePath = path
67 | return this
68 | }
69 |
70 | private var fileName = ""
71 | fun setFileName(name: String): DownLoadHttpUtils {
72 | this.fileName = name
73 | return this
74 | }
75 |
76 | private var deleteWhenException = true
77 | fun setDeleteWhenException(dele: Boolean): DownLoadHttpUtils {
78 | this.deleteWhenException = dele
79 | return this
80 | }
81 |
82 | private val requestBuilder: Request.Builder = Request.Builder()
83 | private var urlBuilder: HttpUrl.Builder? = null
84 |
85 | private val okHttpClient = lazy {
86 | OkHttpClient.Builder()
87 | .readTimeout(readTimeOut, TimeUnit.SECONDS)
88 | .writeTimeout(writeTimeout, TimeUnit.SECONDS)
89 | .connectTimeout(connectTimeout, TimeUnit.SECONDS)
90 | .addInterceptor(interceptor ?: LoggingInterceptor())
91 | .build()
92 | }
93 | private var actionGetTotal: (total: Long) -> Unit? = { _ -> }
94 | private var actionProgress: (position: Long) -> Unit? = { _ -> }
95 | private var actionSuccess: (file: File) -> Unit? = { _ -> }
96 | private var actionFail: (msg: String) -> Unit? = {}
97 |
98 | fun setActionCallBack(
99 | actionGetTotal: (total: Long) -> Unit,
100 | actionProgress: (position: Long) -> Unit,
101 | actionSuccess: (file: File) -> Unit,
102 | actionFail: (msg: String) -> Unit
103 | ): DownLoadHttpUtils {
104 | this.actionGetTotal = actionGetTotal
105 | this.actionProgress = actionProgress
106 | this.actionSuccess = actionSuccess
107 | this.actionFail = actionFail
108 |
109 | return this
110 | }
111 |
112 | private var downCallBack: DownCallBack? = null
113 | fun setDownCallBack(callBack: DownCallBack): DownLoadHttpUtils {
114 | this.downCallBack = callBack
115 | return this
116 | }
117 |
118 | fun initUrl(url: String, params: Map?): DownLoadHttpUtils {
119 | urlBuilder = url.toHttpUrlOrNull()?.newBuilder()
120 | if (params.isNullOrEmpty()) {
121 | return this
122 | }
123 | for ((k, v) in params) {
124 | checkName(k)
125 | urlBuilder?.setQueryParameter(k, v)
126 | }
127 | return this
128 | }
129 |
130 | fun addHeader(map: Map): DownLoadHttpUtils {
131 | requestBuilder.headers(map.toHeaders())
132 | return this
133 | }
134 |
135 | private fun checkName(name: String) {
136 | require(name.isNotEmpty()) { "name is empty" }
137 | }
138 |
139 | fun down() {
140 | if (urlBuilder == null) {
141 | throw IllegalStateException("url not init")
142 | } else {
143 | doDown()
144 | }
145 | }
146 |
147 | var file: File? = null
148 | private fun doDown() {
149 | val startTime = System.currentTimeMillis()
150 | Log.i(TAG, "startTime=$startTime")
151 | val url = urlBuilder?.build()
152 | if (url == null) {
153 | doException("url is null")
154 | return
155 | }
156 | if (isDowning(filePath + fileName)) {
157 | return
158 | }
159 | val request = requestBuilder.url(url).tag(filePath + fileName).build()
160 |
161 | okHttpClient.value.newCall(request).enqueue(object : Callback {
162 | override fun onFailure(call: Call, e: IOException) {
163 | e.printStackTrace()
164 | doException(e.toString())
165 | Log.i(TAG, "download failed")
166 | }
167 |
168 | override fun onResponse(call: Call, response: Response) {
169 | var `is`: InputStream? = null
170 | val buf = ByteArray(buffSize)
171 | var len: Int
172 | var fos: FileOutputStream? = null
173 |
174 | try {
175 | file = if (fileName.isNullOrEmpty()) {
176 | File(filePath)
177 | } else {
178 | val fileDir = File(filePath)
179 | if (!fileDir.exists() || !fileDir.isDirectory) {
180 | fileDir.mkdirs()
181 | }
182 | File(filePath, fileName)
183 | }
184 |
185 | if (file == null) {
186 | doException("file create err,not exists")
187 | return
188 | }
189 |
190 | `is` = response.body?.byteStream() ?: FileInputStream("")
191 | val total = response.body?.contentLength() ?: 0
192 | doGetTotal(total)
193 |
194 | fos = FileOutputStream(file!!)
195 | var sum: Long = 0
196 | while (`is`.read(buf).also { len = it } != -1) {
197 | fos.write(buf, 0, len)
198 | sum += len.toLong()
199 | Log.e(TAG, "download progress : $sum")
200 | doProgress(sum)
201 | }
202 | fos.flush()
203 | Log.e(TAG, "download success")
204 | if (file == null || file?.exists() == false) {
205 | doException("file create err,not exists")
206 | return
207 | } else {
208 | doSuccess(file)
209 | }
210 | file = null
211 | Log.e(TAG, "totalTime=" + (System.currentTimeMillis() - startTime))
212 | } catch (e: Exception) {
213 | e.printStackTrace()
214 | if (deleteWhenException && file?.exists() == true) {
215 | file?.delete()
216 | }
217 | doException(e.message.toString())
218 | Log.e(TAG, "download failed : " + e.message)
219 | } finally {
220 | try {
221 | `is`?.close()
222 | } catch (e: IOException) {
223 | }
224 | try {
225 | fos?.close()
226 | } catch (e: IOException) {
227 | }
228 | file = null
229 | }
230 | }
231 | })
232 | }
233 |
234 | private fun isDowning(tag: String): Boolean {
235 | for (call in okHttpClient.value.dispatcher.runningCalls()) {
236 | if (call.request().tag() == tag) {
237 | return true
238 | }
239 | }
240 | return false
241 | }
242 |
243 | private fun doException(err: String) {
244 | runOnUiThread {
245 | if (downCallBack == null) {
246 | actionFail.invoke(err)
247 | } else {
248 | downCallBack?.fail(err)
249 | }
250 | mainThread = null
251 | }
252 | }
253 |
254 | private fun doSuccess(file: File?) {
255 | runOnUiThread {
256 | if (file == null) {
257 | doException("file not exit")
258 | } else {
259 | if (downCallBack == null) {
260 | actionSuccess.invoke(file)
261 | } else {
262 | downCallBack?.success(file)
263 | }
264 | }
265 | mainThread = null
266 | }
267 | }
268 |
269 | private fun doGetTotal(total: Long) {
270 | runOnUiThread {
271 | if (downCallBack == null) {
272 | actionGetTotal.invoke(total)
273 | } else {
274 | downCallBack?.total(total)
275 | }
276 | }
277 | }
278 |
279 | private fun doProgress(progress: Long) {
280 | runOnUiThread {
281 | if (downCallBack == null) {
282 | actionProgress.invoke(progress)
283 | } else {
284 | downCallBack?.progress(progress)
285 | }
286 | }
287 | }
288 |
289 | private var mainThread: Handler? = null
290 | private fun runOnUiThread(action: () -> Unit) {
291 | if (Looper.myLooper() != Looper.getMainLooper()) { // If we finish marking off of the main thread, we need to
292 | // actually do it on the main thread to ensure correct ordering.
293 | if (mainThread == null) {
294 | mainThread = Handler(Looper.getMainLooper())
295 | }
296 | mainThread?.post {
297 | action.invoke()
298 | }
299 | return
300 | }
301 | action.invoke()
302 | }
303 |
304 |
305 | class LoggingInterceptor : Interceptor {
306 | @Throws(IOException::class)
307 | override fun intercept(chain: Interceptor.Chain): Response {
308 | val request: Request = chain.request()
309 | val startTime = System.nanoTime()
310 | Log.d(
311 | TAG, String.format(
312 | "Sending request %s on %s%n%s",
313 | request.url, chain.connection(), request.headers
314 | )
315 | )
316 | val response: Response = chain.proceed(request)
317 | val endTime = System.nanoTime()
318 | Log.d(
319 | TAG, String.format(
320 | "Received response for %s in %.1fms%n%s",
321 | response.request.url, (endTime - startTime) / 1e6, response.headers
322 | )
323 | )
324 | return response
325 | }
326 |
327 | companion object {
328 | private const val TAG = "LoggingInterceptor"
329 | }
330 | }
331 |
332 | interface DownCallBack {
333 | fun success(file: File)
334 | fun fail(str: String)
335 | fun progress(position: Long)
336 | fun total(total: Long)
337 | }
338 | }
--------------------------------------------------------------------------------