├── .gitignore ├── AwesomeDownloader ├── .gitignore ├── build.gradle ├── consumer-rules.pro ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── jiang │ │ └── awesomedownloader │ │ └── ExampleInstrumentedTest.kt │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── jiang │ │ │ └── awesomedownloader │ │ │ ├── core │ │ │ ├── AwesomeDownloader.kt │ │ │ ├── AwesomeDownloaderOption.kt │ │ │ ├── controller │ │ │ │ └── DownloadController.kt │ │ │ ├── downloader │ │ │ │ ├── DefaultDownloader.kt │ │ │ │ ├── ForegroundServiceDownloader.kt │ │ │ │ └── IDownloader.kt │ │ │ ├── listener │ │ │ │ └── IDownloadListener.kt │ │ │ └── sender │ │ │ │ ├── DefaultNotificationSender.kt │ │ │ │ └── NotificationSender.kt │ │ │ ├── database │ │ │ ├── DownloadTaskManager.kt │ │ │ ├── DownloaderRoomDatabase.kt │ │ │ ├── TaskInfo.kt │ │ │ └── TaskInfoDao.kt │ │ │ ├── http │ │ │ ├── DownloadResponseBody.kt │ │ │ ├── OkHttpManager.kt │ │ │ └── ProgressInterceptor.kt │ │ │ ├── receiver │ │ │ ├── CancelAllReceiver.kt │ │ │ ├── CancelReceiver.kt │ │ │ ├── OpenFileReceiver.kt │ │ │ ├── ResumeReceiver.kt │ │ │ └── StopReceiver.kt │ │ │ └── tool │ │ │ ├── MediaStoreHelper.kt │ │ │ ├── PathSelector.kt │ │ │ └── Tool.kt │ └── res │ │ ├── drawable │ │ ├── ic_baseline_cancel_24.xml │ │ ├── ic_baseline_delete_forever.xml │ │ ├── ic_baseline_pause.xml │ │ ├── ic_baseline_play_arrow.xml │ │ └── ic_download.xml │ │ ├── values-zh-rCN │ │ └── strings.xml │ │ └── values │ │ └── strings.xml │ └── test │ └── java │ └── com │ └── jiang │ └── awesomedownloader │ └── ExampleUnitTest.kt ├── LICENSE ├── README.md ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── local.properties └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/caches 5 | /.idea/libraries 6 | /.idea/modules.xml 7 | /.idea/workspace.xml 8 | /.idea/navEditor.xml 9 | /.idea/assetWizardSettings.xml 10 | .DS_Store 11 | /build 12 | /captures 13 | .externalNativeBuild 14 | .cxx 15 | -------------------------------------------------------------------------------- /AwesomeDownloader/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /AwesomeDownloader/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: 'kotlin-android' 3 | apply plugin: 'kotlin-android-extensions' 4 | apply plugin: 'kotlin-kapt' 5 | apply plugin: 'com.github.dcendents.android-maven' 6 | group = 'com.github.AManCallJiang' 7 | android { 8 | compileSdkVersion 31 9 | buildToolsVersion "30.0.0" 10 | 11 | defaultConfig { 12 | minSdkVersion 19 13 | targetSdkVersion 31 14 | versionCode 1 15 | versionName "1.0" 16 | 17 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 18 | consumerProguardFiles "consumer-rules.pro" 19 | } 20 | 21 | buildTypes { 22 | release { 23 | minifyEnabled false 24 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 25 | } 26 | } 27 | } 28 | 29 | dependencies { 30 | implementation fileTree(dir: "libs", include: ["*.jar"]) 31 | implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" 32 | implementation 'androidx.core:core-ktx:1.3.1' 33 | implementation 'androidx.appcompat:appcompat:1.2.0' 34 | implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0' 35 | testImplementation 'junit:junit:4.12' 36 | androidTestImplementation 'androidx.test.ext:junit:1.1.2' 37 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' 38 | 39 | //OkHttp(网络请求框架) 40 | implementation 'com.squareup.okhttp3:okhttp:3.12.1' 41 | //协程 42 | implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.4" 43 | //room 44 | implementation "androidx.room:room-runtime:2.2.5" 45 | // For Kotlin use kapt instead of annotationProcessor 46 | kapt "androidx.room:room-compiler:2.2.5" 47 | // optional - Kotlin Extensions and Coroutines support for Room 48 | implementation "androidx.room:room-ktx:2.2.5" 49 | 50 | implementation "androidx.lifecycle:lifecycle-service:2.2.0" 51 | 52 | implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.2.0" 53 | implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0" 54 | 55 | } -------------------------------------------------------------------------------- /AwesomeDownloader/consumer-rules.pro: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AManCallJiang/AwesomeDownloader-Android/bade9da016acf5eabff270cece95533bf01387b1/AwesomeDownloader/consumer-rules.pro -------------------------------------------------------------------------------- /AwesomeDownloader/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 -------------------------------------------------------------------------------- /AwesomeDownloader/src/androidTest/java/com/jiang/awesomedownloader/ExampleInstrumentedTest.kt: -------------------------------------------------------------------------------- 1 | package com.jiang.awesomedownloader 2 | 3 | import androidx.test.platform.app.InstrumentationRegistry 4 | import androidx.test.ext.junit.runners.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.getInstrumentation().targetContext 22 | assertEquals("com.jiang.awesomedownloader.test", appContext.packageName) 23 | } 24 | } -------------------------------------------------------------------------------- /AwesomeDownloader/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 21 | 25 | 29 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /AwesomeDownloader/src/main/java/com/jiang/awesomedownloader/core/AwesomeDownloader.kt: -------------------------------------------------------------------------------- 1 | package com.jiang.awesomedownloader.core 2 | 3 | 4 | import android.content.* 5 | import android.os.IBinder 6 | import android.util.Log 7 | import androidx.fragment.app.Fragment 8 | import androidx.fragment.app.FragmentActivity 9 | import androidx.lifecycle.ViewModelProvider 10 | import com.jiang.awesomedownloader.core.sender.DefaultNotificationSender 11 | import com.jiang.awesomedownloader.core.downloader.DefaultDownloader 12 | import com.jiang.awesomedownloader.core.downloader.ForegroundServiceDownloader 13 | import com.jiang.awesomedownloader.core.downloader.IDownloader 14 | import com.jiang.awesomedownloader.core.sender.NotificationSender 15 | import com.jiang.awesomedownloader.database.TaskInfo 16 | import com.jiang.awesomedownloader.tool.TAG 17 | import java.util.* 18 | 19 | 20 | /** 21 | * 22 | * @ProjectName: AwesomeDownloaderDemo 23 | * @ClassName: AwesomeDownloader 24 | * @Description: 门面类 25 | * @Author: 江 26 | * @CreateDate: 2020/8/18 20:04 27 | */ 28 | object AwesomeDownloader { 29 | //设置 30 | val option by lazy { AwesomeDownloaderOption() } 31 | 32 | private lateinit var realDownloader: IDownloader 33 | 34 | private val serviceConnection = object : ServiceConnection { 35 | override fun onServiceConnected(name: ComponentName?, service: IBinder?) { 36 | Log.d(TAG, "onServiceConnected: ") 37 | val binder = service as ForegroundServiceDownloader.DownloadServiceBinder 38 | realDownloader = binder.getService() 39 | } 40 | 41 | override fun onServiceDisconnected(name: ComponentName?) { 42 | Log.d(TAG, "onServiceDisconnected: ") 43 | } 44 | } 45 | 46 | var onDownloadError: LinkedList<(Exception) -> Unit> = LinkedList() 47 | var onDownloadProgressChange: LinkedList<(Long) -> Unit> = LinkedList() 48 | var onDownloadStop: LinkedList<(Long, Long) -> Unit> = LinkedList() 49 | var onDownloadFinished: LinkedList<(String, String) -> Unit> = LinkedList() 50 | 51 | 52 | lateinit var notificationSender: NotificationSender 53 | 54 | /** 55 | * 前台服务模式启动 56 | * @param contextWrapper ContextWrapper 57 | * @return AwesomeDownloader 58 | */ 59 | fun initWithServiceMode(contextWrapper: ContextWrapper): AwesomeDownloader { 60 | initSender(contextWrapper.applicationContext) 61 | val serviceIntent = Intent(contextWrapper, ForegroundServiceDownloader::class.java) 62 | contextWrapper.apply { 63 | startService(serviceIntent) 64 | bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE) 65 | } 66 | 67 | return this 68 | } 69 | 70 | private fun initSender(appContext: Context) { 71 | // if (!this::notificationSender.isInitialized) { 72 | notificationSender = DefaultNotificationSender(appContext) 73 | notificationSender.createNotificationChannel() 74 | //} 75 | } 76 | 77 | /** 78 | * 默认模式启动(与页面绑定,页面销毁时,下载器也会结束生命) 79 | * @param activity FragmentActivity 80 | * @return AwesomeDownloader 81 | */ 82 | fun initWithDefaultMode(activity: FragmentActivity): AwesomeDownloader { 83 | initSender(activity.applicationContext) 84 | realDownloader = ViewModelProvider(activity).get(DefaultDownloader::class.java) 85 | return this 86 | } 87 | 88 | fun initWithDefaultMode(fragment: Fragment): AwesomeDownloader { 89 | initSender(fragment.activity?.applicationContext ?: fragment.requireContext()) 90 | realDownloader = ViewModelProvider(fragment).get(DefaultDownloader::class.java) 91 | return this 92 | } 93 | 94 | fun close(contextWrapper: ContextWrapper) { 95 | val serviceIntent = Intent(contextWrapper, ForegroundServiceDownloader::class.java) 96 | realDownloader.close() 97 | contextWrapper.apply { 98 | unbindService(serviceConnection) 99 | stopService(serviceIntent) 100 | } 101 | 102 | } 103 | 104 | /** 105 | * 任务入队 106 | * @param url String http下载地址 107 | * @param filePath String 文件绝对路径(不包括文件名),一般用路径选择器 108 | * @see com.jiang.awesomedownloader.tool.PathSelector 选择返回的路径 109 | * 110 | * @param fileName String 文件名(包含拓展名,否则无法判断文件类型) 111 | * @return AwesomeDownloader 112 | */ 113 | fun enqueue(url: String, filePath: String, fileName: String): AwesomeDownloader { 114 | realDownloader.enqueue(url, filePath, fileName) 115 | return this 116 | } 117 | 118 | fun stopAll() { 119 | realDownloader.stopAll() 120 | } 121 | 122 | fun resume() { 123 | realDownloader.resumeAndStart() 124 | } 125 | 126 | fun cancelAll() { 127 | realDownloader.cancelAll() 128 | } 129 | 130 | fun cancel() { 131 | realDownloader.cancel() 132 | } 133 | 134 | fun cancel(taskInfo: TaskInfo) { 135 | realDownloader.cancel(taskInfo) 136 | } 137 | 138 | fun clearCache(taskInfo: TaskInfo) { 139 | realDownloader.clearCache(taskInfo) 140 | } 141 | 142 | /** 143 | * 添加错误监听 144 | * @param onError Function1 传入方法的Exception类型参数为捕获的异常 145 | * @return AwesomeDownloader 146 | */ 147 | fun addOnErrorListener(onError: (Exception) -> Unit): AwesomeDownloader { 148 | onDownloadError.addLast(onError) 149 | return this 150 | } 151 | 152 | /** 153 | * 添加任务进度更改监听 154 | * @param onProgressChange Function1 传入方法的Long类型参数为下载进度(0-100) 155 | * @return AwesomeDownloader 156 | */ 157 | fun addOnProgressChangeListener(onProgressChange: (Long) -> Unit): AwesomeDownloader { 158 | onDownloadProgressChange.addLast(onProgressChange) 159 | return this 160 | } 161 | 162 | /** 163 | * 添加任务停止监听 164 | * @param onStop Function2 传入方法的第一个Long类型参数为下载已下载的字节数, 165 | * 第二个Long类型参数为文件总共要下载的字节数 166 | * @return AwesomeDownloader 167 | */ 168 | fun addOnStopListener(onStop: (Long, Long) -> Unit): AwesomeDownloader { 169 | onDownloadStop.addLast(onStop) 170 | return this 171 | } 172 | 173 | /** 174 | * 添加任务完成监听 175 | * @param onFinished Function2 传入方法的第一个String类型参数为文件绝对 176 | * 路径(不包括文件名),第二个String类型参数为文件名 177 | * @return AwesomeDownloader 178 | */ 179 | fun addOnFinishedListener(onFinished: (String, String) -> Unit): AwesomeDownloader { 180 | onDownloadFinished.addLast(onFinished) 181 | return this 182 | } 183 | 184 | /** 185 | * 移除所有监听 186 | */ 187 | fun removeAllOnErrorListener() = onDownloadError.clear() 188 | 189 | fun removeAllOnProgressChangeListener() = onDownloadProgressChange.clear() 190 | 191 | fun removeAllOnStopListener() = onDownloadStop.clear() 192 | 193 | fun removeAllOnFinishedListener() = onDownloadFinished.clear() 194 | 195 | 196 | /** 197 | * 获取当前下载队列所有任务信息的数组 198 | * @return Array<(TaskInfo?)> 199 | */ 200 | fun getDownloadQueueArray() = realDownloader.getDownloadQueueArray() 201 | 202 | /** 203 | * 获取当前下载任务 204 | * @return TaskInfo? 205 | */ 206 | fun getDownloadingTask() = realDownloader.downloadingTask 207 | 208 | /** 209 | * 查询所有任务信息 210 | * @return MutableList 211 | */ 212 | suspend fun queryAllTaskInfo(): MutableList = realDownloader.queryAllTaskInfo() 213 | 214 | /** 215 | * 查询未完成的任务信息 216 | * @return MutableList 217 | */ 218 | suspend fun queryUnfinishedTaskInfo(): MutableList = 219 | realDownloader.queryUnfinishedTaskInfo() 220 | 221 | /** 222 | * 返回包含所有任务信息的LiveData 223 | * @return LiveData> 224 | */ 225 | fun getAllTaskInfoLiveData() = realDownloader.getAllTaskInfoLiveData() 226 | 227 | /** 228 | * 返回包含未完成的任务信息的LiveData 229 | * @return LiveData> 230 | */ 231 | fun getUnfinishedTaskInfoLiveData() = realDownloader.getUnfinishedTaskInfoLiveData() 232 | 233 | /** 234 | *查询已完成的任务信息 235 | * @return MutableList 236 | */ 237 | suspend fun queryFinishedTaskInfo() = realDownloader.queryFinishedTaskInfo() 238 | 239 | /** 240 | * 返回包含已完成的任务信息的LiveData 241 | * @return LiveData> 242 | */ 243 | fun getFinishedTaskInfoLiveData() = realDownloader.getFinishedTaskInfoLiveData() 244 | 245 | suspend fun deleteTaskInfo(taskInfo: TaskInfo) = realDownloader.deleteTaskInfo(taskInfo) 246 | 247 | suspend fun deleteTaskInfoArray(array: Array) = 248 | realDownloader.deleteTaskInfoArray(array) 249 | 250 | suspend fun deleteById(id: Long) = realDownloader.deleteTaskInfoByID(id) 251 | 252 | 253 | fun isDownloading() = !realDownloader.downloadController.isPause() 254 | 255 | } -------------------------------------------------------------------------------- /AwesomeDownloader/src/main/java/com/jiang/awesomedownloader/core/AwesomeDownloaderOption.kt: -------------------------------------------------------------------------------- 1 | package com.jiang.awesomedownloader.core 2 | 3 | /** 4 | * 5 | * @ProjectName: AwesomeDownloader 6 | * @ClassName: AwesomeDownloaderOption 7 | * @Description: java类作用描述 8 | * @Author: 江 9 | * @CreateDate: 2020/8/24 14:18 10 | */ 11 | class AwesomeDownloaderOption { 12 | var timeout: Long = 300 13 | var showNotification = true 14 | var notifyMediaStoreWhenItDone = true 15 | 16 | //未实装 17 | var serviceModeAutoClose = false 18 | var autoCloseTime = 300_000 19 | } -------------------------------------------------------------------------------- /AwesomeDownloader/src/main/java/com/jiang/awesomedownloader/core/controller/DownloadController.kt: -------------------------------------------------------------------------------- 1 | package com.jiang.awesomedownloader.core.controller 2 | 3 | /** 4 | * 5 | * @ProjectName: AwesomeDownloader 6 | * @ClassName: DownloadController 7 | * @Description: java类作用描述 8 | * @Author: 江 9 | * @CreateDate: 2020/8/21 16:11 10 | */ 11 | class DownloadController { 12 | private var workState = 13 | WorkState.RUNNING 14 | @Synchronized 15 | fun pause() { 16 | workState = WorkState.STOP 17 | } 18 | 19 | @Synchronized 20 | fun start() { 21 | workState = WorkState.RUNNING 22 | } 23 | 24 | fun isPause() = workState == WorkState.STOP 25 | } 26 | 27 | enum class WorkState { 28 | RUNNING, STOP 29 | } -------------------------------------------------------------------------------- /AwesomeDownloader/src/main/java/com/jiang/awesomedownloader/core/downloader/DefaultDownloader.kt: -------------------------------------------------------------------------------- 1 | package com.jiang.awesomedownloader.core.downloader 2 | 3 | import android.app.Application 4 | import android.content.Context 5 | import android.widget.Toast 6 | import androidx.lifecycle.* 7 | import com.jiang.awesomedownloader.core.AwesomeDownloader 8 | import com.jiang.awesomedownloader.core.controller.DownloadController 9 | import com.jiang.awesomedownloader.core.listener.IDownloadListener 10 | import com.jiang.awesomedownloader.database.DownloadTaskManager 11 | import com.jiang.awesomedownloader.database.TaskInfo 12 | import com.jiang.awesomedownloader.http.OkHttpManager 13 | import kotlinx.coroutines.CoroutineScope 14 | import okhttp3.OkHttpClient 15 | import java.util.concurrent.ConcurrentLinkedQueue 16 | 17 | /** 18 | * 19 | * @ProjectName: AwesomeDownloaderDemo 20 | * @ClassName: DefaultDownloader 21 | * @Description: java类作用描述 22 | * @Author: 江 23 | * @CreateDate: 2020/11/10 21:31 24 | */ 25 | class DefaultDownloader(application: Application) : IDownloader, AndroidViewModel(application) { 26 | override var appContext: Context = application.applicationContext 27 | override val scope: CoroutineScope = viewModelScope 28 | override val downloadController: DownloadController by lazy { DownloadController() } 29 | override val downloadQueue: ConcurrentLinkedQueue by lazy { ConcurrentLinkedQueue() } 30 | override val taskManager: DownloadTaskManager = DownloadTaskManager(appContext) 31 | override var downloadingTask: TaskInfo? = null 32 | override val okHttpClient: OkHttpClient by lazy { 33 | OkHttpManager.getClient(AwesomeDownloader.option, downloadListener, downloadController) 34 | } 35 | override val downloadListener: IDownloadListener by lazy { createListener() } 36 | 37 | override fun close() { 38 | stopAll() 39 | downloadingTask = null 40 | AwesomeDownloader.notificationSender.cancelDownloadProgressNotification() 41 | } 42 | 43 | override fun onCleared() { 44 | super.onCleared() 45 | close() 46 | } 47 | 48 | 49 | } -------------------------------------------------------------------------------- /AwesomeDownloader/src/main/java/com/jiang/awesomedownloader/core/downloader/ForegroundServiceDownloader.kt: -------------------------------------------------------------------------------- 1 | package com.jiang.awesomedownloader.core.downloader 2 | 3 | import android.content.Context 4 | import android.content.Intent 5 | import android.os.Binder 6 | import android.os.IBinder 7 | import android.util.Log 8 | import androidx.lifecycle.LifecycleService 9 | import androidx.lifecycle.lifecycleScope 10 | import com.jiang.awesomedownloader.core.AwesomeDownloader 11 | import com.jiang.awesomedownloader.core.controller.DownloadController 12 | import com.jiang.awesomedownloader.core.listener.IDownloadListener 13 | import com.jiang.awesomedownloader.database.DownloadTaskManager 14 | import com.jiang.awesomedownloader.database.TaskInfo 15 | import com.jiang.awesomedownloader.http.OkHttpManager 16 | import kotlinx.coroutines.CoroutineScope 17 | import okhttp3.OkHttpClient 18 | import java.util.* 19 | import java.util.concurrent.ConcurrentLinkedQueue 20 | 21 | const val NOTIFICATION_FOREGROUND_SERVICE_ID = 2888 22 | class ForegroundServiceDownloader() : LifecycleService(), IDownloader { 23 | val tag = "ForegroundService" 24 | override lateinit var appContext: Context 25 | override val scope: CoroutineScope = lifecycleScope 26 | override val downloadController: DownloadController by lazy { DownloadController() } 27 | override val downloadQueue: Queue by lazy { ConcurrentLinkedQueue() } 28 | override val taskManager: DownloadTaskManager by lazy { DownloadTaskManager(appContext) } 29 | override var downloadingTask: TaskInfo? = null 30 | override val okHttpClient: OkHttpClient by lazy { 31 | OkHttpManager.getClient( 32 | AwesomeDownloader.option, 33 | downloadListener, 34 | downloadController 35 | ) 36 | } 37 | override val downloadListener: IDownloadListener by lazy { createListener() } 38 | 39 | override fun close() { 40 | stopAll() 41 | downloadingTask = null 42 | stopSelf() 43 | } 44 | 45 | override fun onCreate() { 46 | super.onCreate() 47 | appContext = applicationContext 48 | startForeground( 49 | NOTIFICATION_FOREGROUND_SERVICE_ID, 50 | AwesomeDownloader.notificationSender.buildForegroundServiceNotification() 51 | ) 52 | } 53 | 54 | override fun onBind(intent: Intent): IBinder { 55 | super.onBind(intent) 56 | return DownloadServiceBinder() 57 | 58 | } 59 | 60 | inner class DownloadServiceBinder : Binder() { 61 | fun getService() = this@ForegroundServiceDownloader 62 | } 63 | 64 | override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { 65 | super.onStartCommand(intent, flags, startId) 66 | Log.d(tag, "onStartCommand: ") 67 | return START_NOT_STICKY 68 | } 69 | 70 | override fun onUnbind(intent: Intent?): Boolean { 71 | Log.d(tag, "onUnbind: ") 72 | return super.onUnbind(intent) 73 | } 74 | 75 | override fun onDestroy() { 76 | super.onDestroy() 77 | Log.d(tag, "onDestroy: ") 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /AwesomeDownloader/src/main/java/com/jiang/awesomedownloader/core/downloader/IDownloader.kt: -------------------------------------------------------------------------------- 1 | package com.jiang.awesomedownloader.core.downloader 2 | 3 | import android.content.Context 4 | import android.util.Log 5 | import com.jiang.awesomedownloader.core.AwesomeDownloader 6 | import com.jiang.awesomedownloader.core.controller.DownloadController 7 | import com.jiang.awesomedownloader.database.* 8 | import com.jiang.awesomedownloader.core.listener.IDownloadListener 9 | import com.jiang.awesomedownloader.http.OkHttpManager 10 | import com.jiang.awesomedownloader.tool.MediaStoreHelper 11 | import com.jiang.awesomedownloader.tool.TAG 12 | import com.jiang.awesomedownloader.tool.writeFileInDisk 13 | import kotlinx.coroutines.* 14 | import okhttp3.OkHttpClient 15 | import java.io.File 16 | import java.util.Queue 17 | 18 | /** 19 | * 20 | * @ProjectName: AwesomeDownloaderDemo 21 | * @ClassName: IDownloader 22 | * @Description: java类作用描述 23 | * @Author: 江 24 | * @CreateDate: 2020/11/10 20:45 25 | */ 26 | interface IDownloader { 27 | var appContext: Context 28 | 29 | val scope: CoroutineScope 30 | val downloadController: DownloadController 31 | val downloadQueue: Queue 32 | val taskManager: DownloadTaskManager 33 | var downloadingTask: TaskInfo? 34 | val okHttpClient: OkHttpClient 35 | val downloadListener: IDownloadListener 36 | fun enqueue(url: String, filePath: String, fileName: String) { 37 | scope.launch(Dispatchers.IO) { 38 | try { 39 | val taskInfo = TaskInfo( 40 | System.currentTimeMillis(), 41 | fileName, 42 | filePath, 43 | url, 44 | 0, 45 | 0, 46 | TASK_STATUS_UNINITIALIZED 47 | ) 48 | taskManager.insertTaskInfo(taskInfo) 49 | downloadQueue.offer(taskInfo) 50 | if (downloadingTask == null) switching2NextTask() 51 | 52 | } catch (e: Exception) { 53 | Log.e("download", e.localizedMessage, e) 54 | withContext(Dispatchers.Main) { 55 | AwesomeDownloader.onDownloadError.forEach { it.invoke(e) } 56 | } 57 | } 58 | } 59 | } 60 | 61 | private suspend fun download() { 62 | withContext(Dispatchers.IO) { 63 | if (downloadingTask == null) { 64 | return@withContext 65 | } 66 | val task = downloadingTask!! 67 | val request = OkHttpManager.createRequest(task) 68 | val response = okHttpClient.newCall(request).execute() 69 | writeFileInDisk( 70 | response.body()!!, 71 | File(task.filePath, task.fileName), 72 | task.status == TASK_STATUS_UNFINISHED 73 | ) 74 | Log.d(TAG, "download: switching2NextTask()") 75 | switching2NextTask() 76 | } 77 | } 78 | 79 | private suspend fun switching2NextTask() { 80 | downloadingTask = downloadQueue.poll() 81 | downloadController.start() 82 | download() 83 | } 84 | 85 | fun stopAll() { 86 | downloadController.pause() 87 | downloadQueue.clear() 88 | } 89 | 90 | fun resumeAndStart() { 91 | scope.launch(Dispatchers.IO) { 92 | queryUnfinishedTaskInfo().let { 93 | if (it.isNotEmpty()) { 94 | downloadQueue.clear() 95 | downloadQueue.addAll(it) 96 | downloadController.start() 97 | switching2NextTask() 98 | } 99 | } 100 | } 101 | } 102 | 103 | 104 | fun cancelAll() { 105 | downloadController.pause() 106 | scope.launch(Dispatchers.IO) { 107 | Log.d(TAG, "cancelAll deleteTaskInfoArray: ${getDownloadQueueArray()}") 108 | taskManager.deleteAllUnfinishedTaskInfo() 109 | downloadQueue.forEach { 110 | clearCache(it) 111 | } 112 | downloadQueue.clear() 113 | downloadingTask = null 114 | //downloadController.start() 115 | } 116 | AwesomeDownloader.notificationSender.cancelDownloadProgressNotification() 117 | 118 | } 119 | 120 | fun cancel(taskInfo: TaskInfo) { 121 | scope.launch(Dispatchers.IO) { 122 | if (downloadingTask != null && taskInfo.id == downloadingTask?.id) { 123 | cancel() 124 | } else { 125 | downloadQueue.remove(taskInfo) 126 | taskManager.deleteTaskInfoByID(taskInfo.id) 127 | } 128 | } 129 | } 130 | 131 | fun cancel() { 132 | downloadController.pause() 133 | if (downloadingTask != null) { 134 | scope.launch(Dispatchers.IO) { 135 | Log.d(TAG, "delete: $downloadingTask") 136 | clearCache(downloadingTask!!) 137 | taskManager.deleteTaskInfoByID(downloadingTask!!.id) 138 | downloadQueue.poll() 139 | downloadingTask = null 140 | AwesomeDownloader.notificationSender.cancelDownloadProgressNotification() 141 | delay(2000) 142 | //downloadController.start() 143 | switching2NextTask() 144 | } 145 | } 146 | } 147 | 148 | private fun notifyMediaStore(taskInfo: TaskInfo) { 149 | try { 150 | MediaStoreHelper.notifyMediaStore(taskInfo, appContext) 151 | } catch (e: java.lang.Exception) { 152 | Log.e(TAG, "notifyMediaStore: ${e.message}", e) 153 | AwesomeDownloader.onDownloadError.forEach { it.invoke(e) } 154 | } 155 | } 156 | 157 | fun clearCache(taskInfo: TaskInfo) { 158 | scope.launch(Dispatchers.IO) { 159 | val file = File(taskInfo.getAbsolutePath()) 160 | if (file.exists()) file.delete() 161 | } 162 | } 163 | 164 | fun getDownloadQueueArray() = downloadQueue.toTypedArray() 165 | 166 | 167 | suspend fun queryAllTaskInfo(): MutableList = taskManager.getAllTaskInfo() 168 | 169 | suspend fun queryUnfinishedTaskInfo(): MutableList = 170 | taskManager.getUnfinishedTaskInfo() 171 | 172 | 173 | fun getAllTaskInfoLiveData() = taskManager.getAllTaskInfoLiveData() 174 | 175 | 176 | fun getUnfinishedTaskInfoLiveData() = taskManager.getUnfinishedTaskInfoLiveData() 177 | 178 | 179 | suspend fun queryFinishedTaskInfo() = taskManager.getFinishedTaskInfo() 180 | 181 | 182 | fun getFinishedTaskInfoLiveData() = taskManager.getFinishedTaskInfoLiveData() 183 | 184 | suspend fun deleteTaskInfo(taskInfo: TaskInfo) = taskManager.deleteTaskInfo(taskInfo) 185 | suspend fun deleteTaskInfoArray(array: Array) = taskManager.deleteTaskInfoArray(array) 186 | suspend fun deleteTaskInfoByID(id: Long) = taskManager.deleteTaskInfoByID(id) 187 | 188 | // fun setOnError(onError: (Exception) -> Unit) { 189 | // AwesomeDownloader.onDownloadError = onError 190 | // } 191 | // 192 | // 193 | // fun setOnProgressChange(onProgressChange: (Long) -> Unit) { 194 | // AwesomeDownloader.onDownloadProgressChange = onProgressChange 195 | // } 196 | // 197 | // fun setOnStop(onStop: (Long, Long) -> Unit) { 198 | // AwesomeDownloader.onDownloadStop = onStop 199 | // } 200 | // 201 | // fun setOnFinished(onFinished: (String, String) -> Unit) { 202 | // AwesomeDownloader.onDownloadFinished = onFinished 203 | // } 204 | // 205 | // fun setNotificationSender(sender: NotificationSender) { 206 | // AwesomeDownloader.notificationSender = sender 207 | // } 208 | 209 | fun createListener(): IDownloadListener = object : IDownloadListener { 210 | var progress = 0L 211 | override fun onProgressChange(downloadBytes: Long, totalBytes: Long) { 212 | val newProgress = 213 | (downloadingTask!!.downloadedBytes + downloadBytes) * 100 / if (downloadingTask!!.status == TASK_STATUS_UNINITIALIZED) totalBytes else downloadingTask!!.totalBytes 214 | if (progress != newProgress && newProgress < 100L) { 215 | progress = newProgress 216 | Log.d(TAG, "$progress %") 217 | if (AwesomeDownloader.option.showNotification) { 218 | AwesomeDownloader.notificationSender.showDownloadProgressNotification( 219 | progress.toInt(), downloadingTask?.fileName ?: "null" 220 | ) 221 | } 222 | scope.launch(Dispatchers.Main) { 223 | AwesomeDownloader.onDownloadProgressChange.forEach { it.invoke(progress) } 224 | } 225 | } else if (progress != newProgress && newProgress == 100L) { 226 | onFinish(downloadBytes, totalBytes) 227 | } 228 | } 229 | 230 | override fun onStop(downloadBytes: Long, totalBytes: Long) { 231 | Log.d(TAG, "$downloadBytes b") 232 | val task = downloadingTask 233 | task?.let { 234 | it.downloadedBytes += downloadBytes 235 | if (it.status == TASK_STATUS_UNINITIALIZED) { 236 | it.totalBytes = totalBytes 237 | it.status = TASK_STATUS_UNFINISHED 238 | } 239 | scope.launch(Dispatchers.IO) { taskManager.updateTaskInfo(it) } 240 | AwesomeDownloader.notificationSender.showDownloadStopNotification(task.fileName) 241 | } 242 | scope.launch(Dispatchers.Main) { 243 | AwesomeDownloader.onDownloadStop.forEach { it.invoke(downloadBytes, totalBytes) } 244 | } 245 | } 246 | 247 | override fun onFinish(downloadBytes: Long, totalBytes: Long) { 248 | Log.d(TAG, "onFinish: ") 249 | val task = downloadingTask 250 | task?.let { 251 | if (it.status == TASK_STATUS_UNINITIALIZED) it.totalBytes = totalBytes 252 | it.downloadedBytes += downloadBytes 253 | it.status = TASK_STATUS_FINISH 254 | scope.launch(Dispatchers.IO) { 255 | taskManager.insertTaskInfo(it) 256 | if (AwesomeDownloader.option.notifyMediaStoreWhenItDone) { 257 | notifyMediaStore(it) 258 | } 259 | } 260 | 261 | } 262 | if (AwesomeDownloader.option.showNotification) { 263 | AwesomeDownloader.notificationSender.showDownloadDoneNotification( 264 | downloadingTask?.fileName ?: "null", 265 | downloadingTask?.filePath ?: "null" 266 | ) 267 | AwesomeDownloader.notificationSender.cancelDownloadProgressNotification() 268 | } 269 | scope.launch(Dispatchers.Main) { 270 | AwesomeDownloader.onDownloadFinished.forEach { 271 | it.invoke(task?.filePath ?: "null", task?.fileName ?: "null") 272 | } 273 | } 274 | } 275 | } 276 | 277 | fun close() 278 | 279 | } -------------------------------------------------------------------------------- /AwesomeDownloader/src/main/java/com/jiang/awesomedownloader/core/listener/IDownloadListener.kt: -------------------------------------------------------------------------------- 1 | package com.jiang.awesomedownloader.core.listener 2 | 3 | /** 4 | * 5 | * @ProjectName: AwesomeDownloader 6 | * @ClassName: IDownloadListener 7 | * @Description: java类作用描述 8 | * @Author: 江 9 | * @CreateDate: 2020/8/27 22:29 10 | */ 11 | interface IDownloadListener { 12 | fun onProgressChange(downloadBytes: Long, totalBytes: Long) 13 | fun onFinish(downloadBytes: Long, totalBytes: Long) 14 | fun onStop(downloadBytes: Long, totalBytes: Long) 15 | } -------------------------------------------------------------------------------- /AwesomeDownloader/src/main/java/com/jiang/awesomedownloader/core/sender/DefaultNotificationSender.kt: -------------------------------------------------------------------------------- 1 | package com.jiang.awesomedownloader.core.sender 2 | 3 | import android.app.Notification 4 | import android.app.PendingIntent 5 | import android.content.BroadcastReceiver 6 | import android.content.Context 7 | import android.content.Intent 8 | import android.os.Build 9 | import android.util.Log 10 | import androidx.core.app.NotificationCompat 11 | import com.jiang.awesomedownloader.R 12 | import com.jiang.awesomedownloader.receiver.* 13 | import com.jiang.awesomedownloader.tool.TAG 14 | 15 | 16 | /** 17 | * 18 | * @ProjectName: AwesomeDownloader 19 | * @ClassName: DefaultNotificationSender 20 | * @Description: 默认的通知发送者 21 | * @Author: 江 22 | * @CreateDate: 2020/9/17 15:28 23 | */ 24 | 25 | 26 | class DefaultNotificationSender(context: Context) : NotificationSender(context) { 27 | 28 | private val stopIntent = createIntent(StopReceiver::class.java, "ACTION_STOP") 29 | private val stopPendingIntent = 30 | createPendingIntent(context, stopIntent) 31 | 32 | private val cancelIntent = createIntent(CancelReceiver::class.java, "ACTION_CANCEL") 33 | private val cancelPendingIntent = 34 | createPendingIntent(context, cancelIntent) 35 | 36 | private val cancelAllIntent = createIntent(CancelAllReceiver::class.java, "ACTION_CANCEL_ALL") 37 | private val cancelAllPendingIntent = createPendingIntent(context, cancelAllIntent) 38 | 39 | private val resumeIntent = createIntent(ResumeReceiver::class.java, "ACTION_RESUME") 40 | private val resumePendingIntent = createPendingIntent(context, resumeIntent) 41 | 42 | private fun createIntent(receiverClass: Class, tag: String): Intent { 43 | return Intent(context, receiverClass).apply { action = tag } 44 | } 45 | 46 | private fun createPendingIntent(context: Context, intent: Intent): PendingIntent? = 47 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 48 | PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_IMMUTABLE) 49 | } else { 50 | PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT) 51 | } 52 | 53 | 54 | override fun buildDownloadProgressNotification(progress: Int, fileName: String): Notification { 55 | return NotificationCompat.Builder(context, channelID) 56 | .setSmallIcon(R.drawable.ic_download) 57 | .addAction( 58 | R.drawable.ic_baseline_pause, 59 | context.getString(R.string.stop), 60 | stopPendingIntent 61 | ) 62 | .addAction( 63 | R.drawable.ic_baseline_cancel_24, 64 | context.getString(R.string.cancel), 65 | cancelPendingIntent 66 | ) 67 | .addAction( 68 | R.drawable.ic_baseline_delete_forever, 69 | context.getString(R.string.cancel_all), 70 | cancelAllPendingIntent 71 | ) 72 | .setContentTitle("$fileName ${context.getString(R.string.downloading)}") 73 | .setContentText("$progress%") 74 | .setPriority(NotificationCompat.PRIORITY_LOW) 75 | .setAutoCancel(false) 76 | .setProgress(NOTIFICATION_PROGRESS_MAX, progress, false) 77 | .build() 78 | } 79 | 80 | override fun buildDownloadStopNotification(fileName: String): Notification { 81 | return NotificationCompat.Builder(context, channelID) 82 | .setSmallIcon(R.drawable.ic_download) 83 | .addAction( 84 | R.drawable.ic_baseline_play_arrow, 85 | context.getString(R.string.resume), 86 | resumePendingIntent 87 | ) 88 | .setContentTitle("$fileName ${context.getString(R.string.stoped)}") 89 | .setContentText(context.getString(R.string.notification_content_stop)) 90 | .setPriority(NotificationCompat.PRIORITY_LOW) 91 | .setAutoCancel(false) 92 | .build() 93 | } 94 | 95 | override fun buildDownloadDoneNotification(filePath: String, fileName: String): Notification { 96 | val openFileIntent = Intent(context, OpenFileReceiver::class.java).apply { 97 | action = "ACTION_OPEN" 98 | putExtra("ACTION_OPEN", 0) 99 | putExtra(INTENT_EXTRA_PATH, "$filePath/$fileName") 100 | Log.d(TAG, "showDownloadDoneNotification: $filePath/$fileName") 101 | } 102 | val openPendingIntent = 103 | createPendingIntent(context, openFileIntent) 104 | return NotificationCompat.Builder(context, channelID) 105 | .setSmallIcon(R.drawable.ic_download) 106 | .setContentTitle("$fileName ${context.getString(R.string.done)}") 107 | .setContentText(fileName) 108 | .setPriority(NotificationCompat.PRIORITY_LOW) 109 | .setContentIntent(openPendingIntent) 110 | .setAutoCancel(true) 111 | .build() 112 | } 113 | 114 | } -------------------------------------------------------------------------------- /AwesomeDownloader/src/main/java/com/jiang/awesomedownloader/core/sender/NotificationSender.kt: -------------------------------------------------------------------------------- 1 | package com.jiang.awesomedownloader.core.sender 2 | 3 | import android.app.Notification 4 | import android.app.NotificationChannel 5 | import android.app.NotificationManager 6 | import android.content.Context 7 | import android.os.Build 8 | import androidx.core.app.NotificationCompat 9 | import androidx.core.app.NotificationManagerCompat 10 | import com.jiang.awesomedownloader.R 11 | 12 | const val CHANNEL_NAME = "AwesomeDownloaderNotification" 13 | 14 | const val NOTIFICATION_PROGRESS_MAX = 100 15 | const val NOTIFICATION_DOWNLOAD_ID = 2234 16 | const val NOTIFICATION_DONE_ID = 2277 17 | 18 | abstract class NotificationSender(protected val context: Context) { 19 | protected val channelID: String = this.javaClass.name 20 | val descriptionText = context.getString(R.string.notification_description) 21 | abstract fun buildDownloadProgressNotification(progress: Int, fileName: String): Notification 22 | 23 | abstract fun buildDownloadStopNotification(fileName: String): Notification 24 | 25 | abstract fun buildDownloadDoneNotification(filePath: String, fileName: String): Notification 26 | 27 | /** 28 | * 创建NotificationChannel,但仅在API 26+上创建,因为NotificationChannel类是新的,并且不在支持库中. 29 | * 由于您必须先创建通知渠道,然后才能在 Android 8.0 及更高版本上发布任何通知,因此应在应用启动时立即执行这段代码。 30 | * 反复调用这段代码是安全的,因为创建现有通知渠道不会执行任何操作。 31 | */ 32 | fun createNotificationChannel() { 33 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { 34 | val importance = NotificationManager.IMPORTANCE_LOW 35 | val channel = NotificationChannel(channelID, CHANNEL_NAME, importance) 36 | .apply { description = descriptionText } 37 | val notificationManager: NotificationManager = 38 | context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager 39 | notificationManager.createNotificationChannel(channel) 40 | } 41 | } 42 | 43 | 44 | fun cancelDownloadProgressNotification() { 45 | NotificationManagerCompat.from(context).cancel(NOTIFICATION_DOWNLOAD_ID) 46 | } 47 | 48 | fun showDownloadStopNotification(fileName: String) { 49 | val notification = buildDownloadStopNotification(fileName) 50 | NotificationManagerCompat.from(context).notify(NOTIFICATION_DOWNLOAD_ID, notification) 51 | } 52 | 53 | fun showDownloadDoneNotification(fileName: String, filePath: String) { 54 | val notification = buildDownloadDoneNotification(filePath, fileName) 55 | NotificationManagerCompat.from(context).notify(NOTIFICATION_DONE_ID, notification) 56 | } 57 | 58 | fun showDownloadProgressNotification(progress: Int, fileName: String) { 59 | val notification = buildDownloadProgressNotification(progress, fileName) 60 | NotificationManagerCompat.from(context).notify(NOTIFICATION_DOWNLOAD_ID, notification) 61 | } 62 | open fun buildForegroundServiceNotification(): Notification { 63 | return NotificationCompat.Builder(context, channelID) 64 | .setSmallIcon(R.drawable.ic_download) 65 | .setContentTitle(context.getString(R.string.download_service)) 66 | .setContentText(context.getString(R.string.downloader_ready)) 67 | .setPriority(NotificationCompat.PRIORITY_LOW) 68 | .build() 69 | } 70 | } -------------------------------------------------------------------------------- /AwesomeDownloader/src/main/java/com/jiang/awesomedownloader/database/DownloadTaskManager.kt: -------------------------------------------------------------------------------- 1 | package com.jiang.awesomedownloader.database 2 | 3 | import android.content.Context 4 | import android.util.Log 5 | import androidx.lifecycle.LiveData 6 | import androidx.room.Room 7 | import com.jiang.awesomedownloader.tool.TAG 8 | 9 | 10 | /** 11 | * 12 | * @ProjectName: AwesomeDownloader 13 | * @ClassName: DownloadTaskManager 14 | * @Description: 使用dao操作数据库 15 | * @Author: 江 16 | * @CreateDate: 2020/8/21 22:03 17 | */ 18 | const val DATABASE_NAME = "AwesomeDownloader_DB" 19 | 20 | class DownloadTaskManager(private val appContext: Context) { 21 | 22 | private val database by lazy { 23 | Room.databaseBuilder(appContext, DownloaderRoomDatabase::class.java, DATABASE_NAME).build() 24 | } 25 | 26 | private val dao by lazy { database.getTaskInfoDao() } 27 | 28 | suspend fun getAllTaskInfo(): MutableList = dao.queryAll() 29 | suspend fun getUnfinishedTaskInfo(): MutableList = dao.queryUnfinished() 30 | 31 | fun getAllTaskInfoLiveData(): LiveData> = dao.queryAllAndReturnLiveData() 32 | fun getUnfinishedTaskInfoLiveData(): LiveData> = 33 | dao.queryUnfinishedLiveData() 34 | 35 | suspend fun getFinishedTaskInfo(): MutableList = dao.queryFinished() 36 | fun getFinishedTaskInfoLiveData(): LiveData> = 37 | dao.queryFinishedLiveData() 38 | 39 | suspend fun insertTaskInfo(taskInfo: TaskInfo) { 40 | dao.insert(taskInfo) 41 | } 42 | 43 | suspend fun deleteTaskInfo(taskInfo: TaskInfo): Int { 44 | Log.d(TAG, "deleteTaskInfo $taskInfo") 45 | return dao.delete() 46 | } 47 | 48 | suspend fun deleteTaskInfoArray(taskInfoArray: Array): Int { 49 | Log.d(TAG, "deleteTaskInfo $taskInfoArray") 50 | return dao.deleteArray(taskInfoArray) 51 | } 52 | 53 | suspend fun updateTaskInfo(taskInfo: TaskInfo) { 54 | dao.update(taskInfo) 55 | } 56 | 57 | suspend fun deleteTaskInfoByID(id: Long) = dao.deleteByID(id) 58 | 59 | suspend fun deleteAllUnfinishedTaskInfo() { 60 | dao.deleteAllUnfinishedTaskInfo() 61 | } 62 | } -------------------------------------------------------------------------------- /AwesomeDownloader/src/main/java/com/jiang/awesomedownloader/database/DownloaderRoomDatabase.kt: -------------------------------------------------------------------------------- 1 | package com.jiang.awesomedownloader.database 2 | 3 | import androidx.room.Database 4 | import androidx.room.RoomDatabase 5 | import com.jiang.awesomedownloader.database.TaskInfo 6 | import com.jiang.awesomedownloader.database.TaskInfoDao 7 | 8 | /** 9 | * 10 | * @ProjectName: AwesomeDownloader 11 | * @ClassName: DownloaderRoomDatabase 12 | * @Description: java类作用描述 13 | * @Author: 江 14 | * @CreateDate: 2020/8/21 16:45 15 | */ 16 | @Database(entities = [TaskInfo::class], version = 1, exportSchema = false) 17 | abstract class DownloaderRoomDatabase : RoomDatabase() { 18 | abstract fun getTaskInfoDao(): TaskInfoDao 19 | } -------------------------------------------------------------------------------- /AwesomeDownloader/src/main/java/com/jiang/awesomedownloader/database/TaskInfo.kt: -------------------------------------------------------------------------------- 1 | package com.jiang.awesomedownloader.database 2 | 3 | import androidx.room.Entity 4 | import androidx.room.PrimaryKey 5 | 6 | /** 7 | * 8 | * @ProjectName: AwesomeDownloader 9 | * @ClassName: TaskInfo 10 | * @Description: java类作用描述 11 | * @Author: 江 12 | * @CreateDate: 2020/8/21 16:40 13 | */ 14 | @Entity(tableName = "TaskInfo") 15 | data class TaskInfo( 16 | @PrimaryKey 17 | var id: Long, 18 | var fileName: String, 19 | var filePath: String, 20 | var url: String, 21 | var downloadedBytes: Long, 22 | var totalBytes: Long, 23 | var status: Int 24 | ) { 25 | fun getAbsolutePath() = "$filePath/$fileName" 26 | } 27 | 28 | const val TASK_STATUS_UNINITIALIZED = 0 29 | const val TASK_STATUS_UNFINISHED = 1 30 | const val TASK_STATUS_FINISH = 2 -------------------------------------------------------------------------------- /AwesomeDownloader/src/main/java/com/jiang/awesomedownloader/database/TaskInfoDao.kt: -------------------------------------------------------------------------------- 1 | package com.jiang.awesomedownloader.database 2 | 3 | import androidx.lifecycle.LiveData 4 | import androidx.room.* 5 | /** 6 | * 7 | * @ProjectName: AwesomeDownloader 8 | * @ClassName: TaskInfoDao 9 | * @Description: Dao 10 | * @Author: 江 11 | * @CreateDate: 2020/8/21 16:46 12 | */ 13 | @Dao 14 | interface TaskInfoDao { 15 | @Insert(onConflict = OnConflictStrategy.REPLACE) 16 | suspend fun insert(vararg taskInfo: TaskInfo) 17 | 18 | @Delete 19 | suspend fun delete(vararg taskInfo: TaskInfo): Int 20 | 21 | @Delete 22 | suspend fun deleteArray(taskInfos: Array): Int 23 | 24 | @Update 25 | suspend fun update(vararg taskInfo: TaskInfo) 26 | 27 | @Query("select * from TaskInfo") 28 | suspend fun queryAll(): MutableList 29 | 30 | @Query("select * from TaskInfo") 31 | fun queryAllAndReturnLiveData(): LiveData> 32 | 33 | @Query("select * from TaskInfo where status < $TASK_STATUS_FINISH") 34 | suspend fun queryUnfinished(): MutableList 35 | 36 | @Query("select * from TaskInfo where status < $TASK_STATUS_FINISH") 37 | fun queryUnfinishedLiveData(): LiveData> 38 | 39 | @Query("select * from TaskInfo where status = $TASK_STATUS_FINISH") 40 | suspend fun queryFinished(): MutableList 41 | 42 | @Query("select * from TaskInfo where status = $TASK_STATUS_FINISH") 43 | fun queryFinishedLiveData(): LiveData> 44 | 45 | @Query("delete from TaskInfo where id=:taskInfoID") 46 | suspend fun deleteByID(taskInfoID: Long) 47 | 48 | @Query("delete from TaskInfo where status between $TASK_STATUS_UNINITIALIZED and $TASK_STATUS_UNFINISHED") 49 | suspend fun deleteAllUnfinishedTaskInfo() 50 | } -------------------------------------------------------------------------------- /AwesomeDownloader/src/main/java/com/jiang/awesomedownloader/http/DownloadResponseBody.kt: -------------------------------------------------------------------------------- 1 | package com.jiang.awesomedownloader.http 2 | 3 | import com.jiang.awesomedownloader.core.controller.DownloadController 4 | import com.jiang.awesomedownloader.core.listener.IDownloadListener 5 | import okhttp3.MediaType 6 | import okhttp3.ResponseBody 7 | import okio.* 8 | 9 | /** 10 | * 11 | * @ProjectName: AwesomeDownloader 12 | * @ClassName: DownloadResponseBody 13 | * @Description: java类作用描述 14 | * @Author: 江 15 | * @CreateDate: 2020/8/20 13:49 16 | */ 17 | class DownloadResponseBody( 18 | private val responseBody: ResponseBody, 19 | val listener: IDownloadListener, 20 | val downloadController: DownloadController 21 | ) : 22 | ResponseBody() { 23 | private val bufferedSource: BufferedSource by lazy { Okio.buffer(source(responseBody.source())) } 24 | 25 | override fun contentLength(): Long = responseBody.contentLength() 26 | 27 | override fun contentType(): MediaType? = responseBody.contentType() 28 | 29 | override fun source(): BufferedSource = bufferedSource 30 | 31 | private var downloadBytesRead = 0L 32 | 33 | private fun source(source: Source): Source { 34 | downloadBytesRead = 0L 35 | return object : ForwardingSource(source) { 36 | override fun read(sink: Buffer, byteCount: Long): Long { 37 | val bytesRead = super.read(sink, byteCount) 38 | 39 | if (downloadController.isPause()) { 40 | listener.onStop(downloadBytesRead, contentLength()) 41 | return -1 42 | } 43 | //进度监听 44 | downloadBytesRead += if (bytesRead != -1L) bytesRead else 0 45 | listener.onProgressChange(downloadBytesRead, contentLength()) 46 | // if (downloadBytesRead == contentLength()) { 47 | // listener.onFinish(downloadBytesRead, contentLength()) 48 | // } 49 | 50 | 51 | // val old = downloadBytesRead * 100 / contentLength() 52 | // downloadBytesRead += if (bytesRead != -1L) bytesRead else 0 53 | // val newV = downloadBytesRead * 100 / contentLength() 54 | // if (old != newV) { 55 | // listener.onProgressChange(newV) 56 | // if (downloadBytesRead >= contentLength()) { 57 | // listener.onFinish(downloadBytesRead, contentLength()) 58 | // } 59 | // } 60 | return bytesRead 61 | } 62 | } 63 | } 64 | } -------------------------------------------------------------------------------- /AwesomeDownloader/src/main/java/com/jiang/awesomedownloader/http/OkHttpManager.kt: -------------------------------------------------------------------------------- 1 | package com.jiang.awesomedownloader.http 2 | 3 | import com.jiang.awesomedownloader.database.TaskInfo 4 | import com.jiang.awesomedownloader.core.AwesomeDownloaderOption 5 | import com.jiang.awesomedownloader.core.listener.IDownloadListener 6 | import com.jiang.awesomedownloader.core.controller.DownloadController 7 | import okhttp3.OkHttpClient 8 | import okhttp3.Request 9 | import java.util.concurrent.TimeUnit 10 | 11 | /** 12 | * 13 | * @ProjectName: AwesomeDownloaderDemo 14 | * @ClassName: OkHttpManager 15 | * @Description: java类作用描述 16 | * @Author: 江 17 | * @CreateDate: 2020/9/21 14:47 18 | */ 19 | object OkHttpManager { 20 | 21 | fun getClient( 22 | option: AwesomeDownloaderOption, 23 | downloadListener: IDownloadListener, 24 | downloadController: DownloadController 25 | ): OkHttpClient = 26 | OkHttpClient.Builder() 27 | .addInterceptor(ProgressInterceptor(downloadListener, downloadController)) 28 | .connectTimeout(option.timeout, TimeUnit.SECONDS) 29 | .build() 30 | 31 | 32 | fun createRequest(taskInfo: TaskInfo): Request = 33 | Request.Builder().url(taskInfo.url) 34 | .addHeader("Range", "bytes=${taskInfo.downloadedBytes}-") 35 | .build() 36 | } -------------------------------------------------------------------------------- /AwesomeDownloader/src/main/java/com/jiang/awesomedownloader/http/ProgressInterceptor.kt: -------------------------------------------------------------------------------- 1 | package com.jiang.awesomedownloader.http 2 | 3 | 4 | import com.jiang.awesomedownloader.core.controller.DownloadController 5 | import com.jiang.awesomedownloader.core.listener.IDownloadListener 6 | import okhttp3.Interceptor 7 | import okhttp3.Response 8 | 9 | /** 10 | * 11 | * @ProjectName: AwesomeDownloader 12 | * @ClassName: ProgressInterceptor 13 | * @Description: java类作用描述 14 | * @Author: 江 15 | * @CreateDate: 2020/8/21 21:57 16 | */ 17 | 18 | class ProgressInterceptor( 19 | private val listener: IDownloadListener, 20 | private val downloadController: DownloadController 21 | ) : Interceptor { 22 | override fun intercept(chain: Interceptor.Chain): Response { 23 | val originalResponse: Response = chain.proceed(chain.request()) 24 | return originalResponse.newBuilder() 25 | .body( 26 | DownloadResponseBody( 27 | originalResponse.body()!!, 28 | listener, 29 | downloadController 30 | ) 31 | ) 32 | .build() 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /AwesomeDownloader/src/main/java/com/jiang/awesomedownloader/receiver/CancelAllReceiver.kt: -------------------------------------------------------------------------------- 1 | package com.jiang.awesomedownloader.receiver 2 | 3 | import android.content.BroadcastReceiver 4 | import android.content.Context 5 | import android.content.Intent 6 | import com.jiang.awesomedownloader.core.AwesomeDownloader 7 | 8 | class CancelAllReceiver : BroadcastReceiver() { 9 | 10 | override fun onReceive(context: Context, intent: Intent) { 11 | AwesomeDownloader.cancelAll() 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /AwesomeDownloader/src/main/java/com/jiang/awesomedownloader/receiver/CancelReceiver.kt: -------------------------------------------------------------------------------- 1 | package com.jiang.awesomedownloader.receiver 2 | 3 | import android.content.BroadcastReceiver 4 | import android.content.Context 5 | import android.content.Intent 6 | import com.jiang.awesomedownloader.core.AwesomeDownloader 7 | 8 | class CancelReceiver : BroadcastReceiver() { 9 | 10 | override fun onReceive(context: Context, intent: Intent) { 11 | // This method is called when the BroadcastReceiver is receiving an Intent broadcast. 12 | AwesomeDownloader.cancel() 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /AwesomeDownloader/src/main/java/com/jiang/awesomedownloader/receiver/OpenFileReceiver.kt: -------------------------------------------------------------------------------- 1 | package com.jiang.awesomedownloader.receiver 2 | 3 | import android.content.BroadcastReceiver 4 | import android.content.Context 5 | import android.content.Intent 6 | import android.net.Uri 7 | import android.util.Log 8 | import android.widget.Toast 9 | import com.jiang.awesomedownloader.tool.* 10 | import java.io.File 11 | 12 | const val INTENT_EXTRA_PATH = "PATH" 13 | 14 | class OpenFileReceiver : BroadcastReceiver() { 15 | 16 | override fun onReceive(context: Context, intent: Intent) { 17 | try { 18 | val stringExtra = intent.getStringExtra(INTENT_EXTRA_PATH) 19 | Toast.makeText(context, stringExtra, Toast.LENGTH_SHORT).show() 20 | Log.d(TAG, "onReceive: $stringExtra") 21 | val file = File(stringExtra) 22 | if (file.exists()) { 23 | val uriFromFile = Uri.fromFile(file) 24 | val type = getMimeType(file.name) 25 | val intent = Intent(Intent.ACTION_VIEW) 26 | intent.apply { 27 | flags = Intent.FLAG_ACTIVITY_NEW_TASK 28 | setDataAndType(uriFromFile, type) 29 | context.startActivity(this) 30 | } 31 | } 32 | } catch (e: Exception) { 33 | Log.e(TAG, "onReceive: ${e.localizedMessage}", e) 34 | Toast.makeText(context, "${e.message}", Toast.LENGTH_SHORT).show() 35 | } 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /AwesomeDownloader/src/main/java/com/jiang/awesomedownloader/receiver/ResumeReceiver.kt: -------------------------------------------------------------------------------- 1 | package com.jiang.awesomedownloader.receiver 2 | 3 | import android.content.BroadcastReceiver 4 | import android.content.Context 5 | import android.content.Intent 6 | import com.jiang.awesomedownloader.core.AwesomeDownloader 7 | 8 | class ResumeReceiver : BroadcastReceiver() { 9 | 10 | override fun onReceive(context: Context, intent: Intent) { 11 | // This method is called when the BroadcastReceiver is receiving an Intent broadcast. 12 | AwesomeDownloader.resume() 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /AwesomeDownloader/src/main/java/com/jiang/awesomedownloader/receiver/StopReceiver.kt: -------------------------------------------------------------------------------- 1 | package com.jiang.awesomedownloader.receiver 2 | 3 | import android.content.BroadcastReceiver 4 | import android.content.Context 5 | import android.content.Intent 6 | import android.util.Log 7 | import com.jiang.awesomedownloader.core.AwesomeDownloader 8 | import com.jiang.awesomedownloader.tool.TAG 9 | 10 | class StopReceiver : BroadcastReceiver() { 11 | 12 | override fun onReceive(context: Context, intent: Intent) { 13 | Log.d(TAG, "onReceive: stop") 14 | AwesomeDownloader.stopAll() 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /AwesomeDownloader/src/main/java/com/jiang/awesomedownloader/tool/MediaStoreHelper.kt: -------------------------------------------------------------------------------- 1 | package com.jiang.awesomedownloader.tool 2 | 3 | import android.content.ContentValues 4 | import android.content.Context 5 | import android.media.MediaScannerConnection 6 | import android.os.Build 7 | import android.provider.MediaStore 8 | import android.util.Log 9 | import com.jiang.awesomedownloader.core.AwesomeDownloader 10 | import com.jiang.awesomedownloader.database.TaskInfo 11 | 12 | 13 | /** 14 | * 15 | * @ProjectName: AwesomeDownloader 16 | * @ClassName: MediaStoreHelper 17 | * @Description: java类作用描述 18 | * @Author: 江 19 | * @CreateDate: 2020/8/29 22:08 20 | */ 21 | object MediaStoreHelper { 22 | fun notifyMediaStore(taskInfo: TaskInfo, appContext: Context) { 23 | if (AwesomeDownloader.option.notifyMediaStoreWhenItDone) { 24 | val fileName = taskInfo.fileName 25 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { 26 | val resolver = appContext.contentResolver 27 | val mimeType = getMimeType(fileName) 28 | Log.d(TAG, "notifyMediaStore: mimeType:$mimeType") 29 | when { 30 | isVideoFile(fileName) -> { 31 | val contentUri = 32 | MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY) 33 | val values = ContentValues().apply { 34 | put(MediaStore.Video.Media.DISPLAY_NAME, fileName) 35 | put(MediaStore.MediaColumns.MIME_TYPE, mimeType) 36 | } 37 | Log.d( 38 | TAG, 39 | "notifyMediaStore: ${resolver?.insert(contentUri, values).toString()}" 40 | ) 41 | } 42 | isAudioFile(fileName) -> { 43 | val contentUri = 44 | MediaStore.Audio.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY) 45 | val values = ContentValues().apply { 46 | put(MediaStore.Audio.Media.DISPLAY_NAME, fileName) 47 | put(MediaStore.MediaColumns.MIME_TYPE, mimeType) 48 | } 49 | Log.d( 50 | TAG, 51 | "notifyMediaStore: ${resolver?.insert(contentUri, values).toString()}" 52 | ) 53 | } 54 | isImageFile(fileName) -> { 55 | val contentUri = 56 | MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY) 57 | val values = ContentValues().apply { 58 | put(MediaStore.Images.Media.DISPLAY_NAME, fileName) 59 | put(MediaStore.MediaColumns.MIME_TYPE, mimeType) 60 | } 61 | Log.d( 62 | TAG, 63 | "notifyMediaStore: ${resolver?.insert(contentUri, values).toString()}" 64 | ) 65 | 66 | } 67 | else -> { 68 | Log.d(TAG, "notifyMediaStore: 类型不匹配 $fileName") 69 | return 70 | } 71 | } 72 | } else { 73 | notifyScanFile(taskInfo, appContext) 74 | } 75 | 76 | } 77 | } 78 | 79 | private fun notifyScanFile(taskInfo: TaskInfo, appContext: Context) { 80 | val fileName = taskInfo.fileName 81 | val mimeType = getMimeType(fileName) 82 | 83 | if (mimeType.isNullOrEmpty()) { 84 | MediaScannerConnection.scanFile( 85 | appContext, 86 | arrayOf(taskInfo.getAbsolutePath()), 87 | arrayOf(mimeType) 88 | ) { path, uri -> 89 | Log.d( 90 | TAG, 91 | "notifyScanFile: path:$path fileName:$fileName uri:$uri mimeType:$mimeType" 92 | ) 93 | } 94 | } else { 95 | Log.d(TAG, "notifyScanFile: 类型不匹配 $fileName $mimeType") 96 | } 97 | } 98 | } -------------------------------------------------------------------------------- /AwesomeDownloader/src/main/java/com/jiang/awesomedownloader/tool/PathSelector.kt: -------------------------------------------------------------------------------- 1 | package com.jiang.awesomedownloader.tool 2 | 3 | import android.content.Context 4 | import android.os.Environment 5 | 6 | 7 | /** 8 | * 9 | * @ProjectName: AwesomeDownloader 10 | * @ClassName: PathSelector 11 | * @Description: 路径选择工具 12 | * @Author: 江 13 | * @CreateDate: 2020/8/29 14:48 14 | */ 15 | class PathSelector(private val context: Context) { 16 | 17 | /** 18 | * 返回手机内部储存的应用缓存路径 (/data/user/0/{packageName}/cache) 19 | * @return String 20 | */ 21 | fun getCacheDirPath(): String = context.cacheDir.absolutePath 22 | 23 | /** 24 | * 返回手机外部储存的应用缓存路径 (/storage/emulated/0/Android/data/{packageName}/cache) 25 | * @return String 26 | */ 27 | fun getExternalCacheDirPath(): String = context.externalCacheDir?.absolutePath!! 28 | 29 | 30 | /** 31 | * 返回手机外部储存的应用图片路径 (/storage/emulated/0/Android/data/{packageName}/files/Pictures) 32 | * @return String 33 | */ 34 | fun getPicturesDirPath(): String = 35 | context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)?.absolutePath!! 36 | 37 | /** 38 | * 返回手机外部储存的应用影片路径 (/storage/emulated/0/Android/data/{packageName}/files/Movies) 39 | * @return String 40 | */ 41 | fun getVideosDirPath(): String = 42 | context.getExternalFilesDir(Environment.DIRECTORY_MOVIES)?.absolutePath!! 43 | 44 | /** 45 | * 返回手机外部储存的应用音乐路径 (/storage/emulated/0/Android/data/{packageName}/files/Music) 46 | * @return String 47 | */ 48 | fun getMusicDirPath(): String = 49 | context.getExternalFilesDir(Environment.DIRECTORY_MUSIC)?.absolutePath!! 50 | 51 | /** 52 | * 返回手机外部储存的应用下载文件路径 (/storage/emulated/0/Android/data/{packageName}/files/Download) 53 | * @return String 54 | */ 55 | fun getDownloadsDirPath(): String = 56 | context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.absolutePath!! 57 | 58 | // /storage/emulated/0 59 | /** 60 | * 返回手机外部储存的根目录 (/storage/emulated/0) 61 | * @return String 62 | */ 63 | fun getExternalRootDir(): String = Environment.getExternalStorageDirectory().absolutePath 64 | 65 | } -------------------------------------------------------------------------------- /AwesomeDownloader/src/main/java/com/jiang/awesomedownloader/tool/Tool.kt: -------------------------------------------------------------------------------- 1 | package com.jiang.awesomedownloader.tool 2 | 3 | import android.os.StrictMode 4 | import kotlinx.coroutines.Dispatchers 5 | import kotlinx.coroutines.withContext 6 | import okhttp3.ResponseBody 7 | import java.io.File 8 | import java.io.FileOutputStream 9 | import java.net.URLConnection 10 | 11 | const val TAG = "AwesomeDownloader" 12 | const val WRITE_BUFFER_SIZE = 4096 13 | suspend fun writeFileInDisk(body: ResponseBody, target: File, isAppend: Boolean) { 14 | withContext(Dispatchers.IO) { 15 | val buffer = ByteArray(WRITE_BUFFER_SIZE) 16 | val inputStream = body.byteStream() 17 | val outputStream = FileOutputStream(target, isAppend) 18 | inputStream.use { ips -> 19 | outputStream.use { ops -> 20 | while (true) { 21 | val read = ips.read(buffer) 22 | if (read == -1) break 23 | ops.write(buffer, 0, read) 24 | } 25 | ops.flush() 26 | } 27 | } 28 | } 29 | 30 | } 31 | 32 | fun isVideoFile(fileName: String): Boolean { 33 | val s = getFileExtension(fileName) 34 | return s.equals("mp4", ignoreCase = true) || 35 | s.equals("mpg", ignoreCase = true) || 36 | s.equals("mpeg", ignoreCase = true) || 37 | s.equals("avi", ignoreCase = true) || 38 | s.equals("rm", ignoreCase = true) || 39 | s.equals("rmvb", ignoreCase = true) || 40 | s.equals("mov", ignoreCase = true) || 41 | s.equals("wmv", ignoreCase = true) || 42 | s.equals("asf", ignoreCase = true) || 43 | s.equals("dat", ignoreCase = true) 44 | } 45 | 46 | fun isAudioFile(fileName: String): Boolean { 47 | val s = getFileExtension(fileName) 48 | return s.equals("mp3", ignoreCase = true) || 49 | s.equals("wma", ignoreCase = true) || 50 | s.equals("wav", ignoreCase = true) || 51 | s.equals("mid", ignoreCase = true) 52 | } 53 | 54 | fun isImageFile(fileName: String): Boolean { 55 | val s = getFileExtension(fileName) 56 | return s.contains("bmp", ignoreCase = true) || 57 | s.contains("jpg", ignoreCase = true) || 58 | s.contains("jpeg", ignoreCase = true) || 59 | s.contains("png", ignoreCase = true) || 60 | s.contains("gif", ignoreCase = true) 61 | } 62 | 63 | fun isApkFile(fileName: String): Boolean { 64 | val s = getFileExtension(fileName) 65 | return s.contains("apk", ignoreCase = true) 66 | 67 | } 68 | 69 | const val STRING_DOT = "." 70 | fun getFileExtension(fileName: String): String { 71 | val splitStrings = fileName.split(STRING_DOT) 72 | if (splitStrings.size <= 1) return "" 73 | val extension = splitStrings[splitStrings.size - 1] 74 | // Log.d(TAG, "getFileExtension: $extension") 75 | return extension 76 | } 77 | 78 | //fun getMimeType(fileName: String): String { 79 | // return when { 80 | // isImageFile(fileName) -> "image/${getFileExtension(fileName)}" 81 | // isVideoFile(fileName) -> "video/${getFileExtension(fileName)}" 82 | // isAudioFile(fileName) -> "audio/${getFileExtension(fileName)}" 83 | // isApkFile(fileName) -> "application/vnd.android.package-archive" 84 | // else -> "" 85 | // } 86 | //} 87 | fun getMimeType(fileName: String): String? { 88 | return URLConnection.getFileNameMap().getContentTypeFor(fileName) 89 | } 90 | 91 | //报错:exposed beyond app through ClipData.Item.getUri,使用 92 | fun exposedFileUri() { 93 | val builder = StrictMode.VmPolicy.Builder() 94 | StrictMode.setVmPolicy(builder.build()) 95 | builder.detectFileUriExposure() 96 | } -------------------------------------------------------------------------------- /AwesomeDownloader/src/main/res/drawable/ic_baseline_cancel_24.xml: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /AwesomeDownloader/src/main/res/drawable/ic_baseline_delete_forever.xml: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /AwesomeDownloader/src/main/res/drawable/ic_baseline_pause.xml: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /AwesomeDownloader/src/main/res/drawable/ic_baseline_play_arrow.xml: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /AwesomeDownloader/src/main/res/drawable/ic_download.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /AwesomeDownloader/src/main/res/values-zh-rCN/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 停止 4 | 取消 5 | 取消所有 6 | (下载中) 7 | 恢复下载 8 | (已停止) 9 | 下载已停止。 10 | (下载完成) 11 | 此通知频道用来显示下载进度 12 | 下载服务已准备就绪。 13 | 下载服务 14 | -------------------------------------------------------------------------------- /AwesomeDownloader/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | stop 4 | cancel 5 | cancel all 6 | (downloading) 7 | resume 8 | (stoped) 9 | The download has been stopped. 10 | (done) 11 | Downloader channel to show progress 12 | Download service is ready. 13 | download service 14 | -------------------------------------------------------------------------------- /AwesomeDownloader/src/test/java/com/jiang/awesomedownloader/ExampleUnitTest.kt: -------------------------------------------------------------------------------- 1 | package com.jiang.awesomedownloader 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 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AwesomeDownloader 2 | 3 | #### 介绍 4 | **_AwesomeDownloader 是基于OkHttp和kotlin协程实现的下载器,它能在后台进行下载任务并轻松地让您在下载文件时获取进度,它能随时停止、恢复、取消任务,还可以方便地查询下载的任务和已完成的任务的信息。_** 5 | 6 | #### 功能&特性 7 | 8 | 9 | :star: **下载文件** 10 | 11 | :star: **监听下载** 12 | 13 | :star: **断点续传** 14 | 15 | :star: **随时控制下载** 16 | 17 | :star: **查询下载任务 (支持返回LiveData)** 18 | 19 | :star: **可通过通知栏显示下载情况** 20 | 21 | :star: **下载多媒体文件加入多媒体库** 22 | 23 | :star: **自动/手动清除缓存文件** 24 | 25 | :star: **支持链式调用** 26 | 27 | 28 | #### 导入依赖 29 | 30 | 1. 把它添加到你的根目录build.gradle中,在repositories的最后: 31 | ```groovy 32 | 33 | allprojects { 34 | repositories { 35 | ... 36 | maven { url 'https://jitpack.io' } 37 | } 38 | } 39 | 40 | ``` 41 | 42 | 2. 添加依赖: 43 | ![version](https://jitpack.io/v/com.gitee.jiang_li_jie_j/awesome-downloader.svg) 44 | ```groovy 45 | dependencies { 46 | implementation 'com.gitee.jiang_li_jie_j:awesome-downloader:v1.2.2-alpha' 47 | } 48 | 49 | ``` 50 | 51 | 52 | #### 使用说明 53 | 54 | 1.申请读写权限,网络权限 55 | 56 | 2.初始化下载器,传入Application的context 57 | 58 | kotlin: 59 | ```kotlin 60 | //默认模式启动(与页面绑定,页面销毁时,下载器也会结束生命)传入FragmentActivity或Fragment 61 | AwesomeDownloader.initWithDefaultMode(requireActivity()) 62 | 63 | //前台服务模式启动(独立启动,直至服务被kill或关闭)传入能创建服务的ContextWrapper 64 | AwesomeDownloader.initWithServiceMode(this) 65 | ``` 66 | java: 67 | ```java 68 | //默认模式启动(与页面绑定,页面销毁时,下载器也会结束生命)传入FragmentActivity或Fragment 69 | AwesomeDownloader.INSTANCE.initWithDefaultMode(this); 70 | 71 | //前台服务模式启动(独立启动,直至服务被kill或关闭)传入能创建服务的ContextWrapper 72 | AwesomeDownloader.INSTANCE.initWithServiceMode(this); 73 | ``` 74 | 3.下载文件 75 | 76 | kotlin: 77 | ```kotlin 78 | val url = "https://images.gitee.com/uploads/images/2020/0919/155031_538a3406_5577115.png" 79 | //获取应用私有照片储存路径 80 | val filePath = PathSelector(applicationContext).getPicturesDirPath() 81 | //加入下载队列 82 | AwesomeDownloader.enqueue(url,filePath,"test.png") 83 | ``` 84 | java: 85 | ```java 86 | String url = "https://images.gitee.com/uploads/images/2020/0919/155031_538a3406_5577115.png"; 87 | //获取应用私有照片储存路径 88 | String filePath = new PathSelector(applicationContext).getPicturesDirPath(); 89 | //加入下载队列 90 | AwesomeDownloader.INSTANCE.enqueue(url, filePath, "test.png"); 91 | ``` 92 | 4.下载控制 93 | 94 | kotlin: 95 | ```kotlin 96 | //停止全部 97 | AwesomeDownloader.stopAll() 98 | //恢复下载 99 | AwesomeDownloader.resume() 100 | //取消当前 101 | AwesomeDownloader.cancel() 102 | //取消全部 103 | AwesomeDownloader.cancelAll() 104 | ``` 105 | 106 | 5.添加监听&移除监听 107 | 108 | kotlin: 109 | ```kotlin 110 | //添加监听 111 | AwesomeDownloader.addOnProgressChangeListener{ progress -> 112 | //do something... 113 | }.addOnStopListener{ downloadBytes, totalBytes -> 114 | //do something... 115 | }.addOnFinishedListener{ filePath, fileName -> 116 | //do something... 117 | }.addOnErrorListener{ exception -> 118 | //do something... 119 | } 120 | 121 | //移除全部进度监听 122 | AwesomeDownloader.removeAllOnProgressChangeListener() 123 | 124 | //移除最后一个进度监听 125 | AwesomeDownloader.onDownloadProgressChange.removeLast() 126 | 127 | //移除最前的进度监听 128 | AwesomeDownloader.onDownloadProgressChange.removeFirst() 129 | ``` 130 | 131 | java: 132 | ```java 133 | //添加监听 134 | AwesomeDownloader.INSTANCE 135 | .addOnProgressChangeListener(progress -> { 136 | //do something 137 | return null; 138 | }).addOnStopListener((downloadBytes, totalBytes) -> { 139 | //do something 140 | return null; 141 | }).addOnFinishedListener((filePath, fileName) -> { 142 | //do something 143 | return null; 144 | }).addOnErrorListener(exception -> { 145 | //do something 146 | return null; 147 | }); 148 | 149 | //移除全部进度监听 150 | AwesomeDownloader.INSTANCE.removeAllOnProgressChangeListener(); 151 | 152 | //移除最后一个进度监听 153 | AwesomeDownloader.INSTANCE.getOnDownloadProgressChange() 154 | .removeLast(); 155 | 156 | //移除最前的进度监听 157 | AwesomeDownloader.INSTANCE.getOnDownloadProgressChange() 158 | .removeFirst(); 159 | ``` 160 | 161 | 6.设置自定义通知栏 162 | 163 | (默认显示的通知栏) 164 | 165 | ![默认显示的通知栏](https://images.gitee.com/uploads/images/2020/0919/155031_538a3406_5577115.png) 166 | 167 | 设置中确保showNotification为true 168 | ```kotlin 169 | AwesomeDownloader.option.showNotification = true 170 | ``` 171 | 调用setNotificationSender() 172 | 173 | override 抽象类NotificationSender 的三个方法 174 | 175 | kotlin: 176 | ```kotlin 177 | AwesomeDownloader.setNotificationSender(object : NotificationSender(applicationContext) { 178 | //创建显示任务下载进度的Notification 179 | override fun buildDownloadProgressNotification( 180 | progress: Int, 181 | fileName: String 182 | ): Notification { 183 | return NotificationCompat.Builder(context, CHANNEL_ID) 184 | .setSmallIcon(R.drawable.ic_baseline_adb_24) 185 | .setContentTitle("$fileName 下载中") 186 | .setContentText("$progress%") 187 | .setPriority(NotificationCompat.PRIORITY_HIGH) 188 | .build() 189 | } 190 | 191 | //创建显示任务下载停止的Notification 192 | override fun buildDownloadStopNotification(fileName: String): Notification { 193 | return NotificationCompat.Builder(context, CHANNEL_ID) 194 | .setSmallIcon(R.drawable.ic_baseline_adb_24) 195 | .setContentTitle("$fileName Stop") 196 | .setContentText("Stop") 197 | .setPriority(NotificationCompat.PRIORITY_HIGH) 198 | .build() 199 | } 200 | 201 | //创建显示任务下载完成的Notification 202 | override fun buildDownloadDoneNotification( 203 | filePath: String, 204 | fileName: String 205 | ): Notification { 206 | Log.d(TAG, "buildDownloadDoneNotification: start") 207 | return if (isImageFile(fileName)) { 208 | val bitmap = 209 | BitmapFactory.decodeFile("$filePath/$fileName") 210 | Log.d(TAG, "buildDownloadDoneNotification: done") 211 | NotificationCompat.Builder(context, CHANNEL_ID) 212 | .setSmallIcon(R.drawable.ic_baseline_adb_24) 213 | .setContentTitle("$fileName Done") 214 | .setContentText("Done") 215 | .setStyle( 216 | NotificationCompat.BigPictureStyle() 217 | .bigPicture(bitmap) 218 | .bigLargeIcon(null) 219 | ) 220 | .setPriority(NotificationCompat.PRIORITY_HIGH) 221 | .build() 222 | 223 | } else { 224 | NotificationCompat.Builder(context, CHANNEL_ID) 225 | .setSmallIcon(R.drawable.ic_baseline_adb_24) 226 | .setContentTitle("$fileName Done") 227 | .setContentText("Done") 228 | .setPriority(NotificationCompat.PRIORITY_HIGH) 229 | .build() 230 | } 231 | } 232 | }) 233 | ``` 234 | 235 | _(通过setNotificationSender()设置的通知栏)_ 236 | 237 | ![自定义显示的通知栏](https://images.gitee.com/uploads/images/2020/0919/153803_33f283b0_5577115.png) 238 | 239 | _(通知栏效果可能因为Android版本不同和手机厂商不同而效果不一致)_ 240 | 241 | 242 | 243 | 7.查询下载任务 244 | 245 | kotlin: 246 | ```kotlin 247 | lifecycleScope.launch(Dispatchers.IO) { 248 | //获取全部任务信息 249 | AwesomeDownloader.queryAllTaskInfo() 250 | //获取完成的任务信息 251 | AwesomeDownloader.queryFinishedTaskInfo() 252 | //获取完成的任务信息 253 | AwesomeDownloader.queryUnfinishedTaskInfo() 254 | //根据id删除数据库中的任务记录 255 | AwesomeDownloader.deleteById(id) 256 | } 257 | 258 | //获取当前下载中的任务 259 | AwesomeDownloader.getDownloadingTask() 260 | 261 | //获取队列中的任务 262 | AwesomeDownloader.getDownloadQueueArray() 263 | 264 | ``` 265 | 266 | java: 267 | ```java 268 | //获取全部任务信息 269 | AwesomeDownloader.INSTANCE.getAllTaskInfoLiveData().getValue(); 270 | 271 | //获取完成的任务信息 272 | AwesomeDownloader.INSTANCE.getFinishedTaskInfoLiveData().getValue(); 273 | 274 | //获取完成的任务信息 275 | AwesomeDownloader.INSTANCE.getUnfinishedTaskInfoLiveData().getValue(); 276 | 277 | //获取当前下载中的任务 278 | AwesomeDownloader.INSTANCE.getDownloadingTask(); 279 | 280 | //获取队列中的任务 281 | AwesomeDownloader.INSTANCE.getDownloadQueueArray(); 282 | ``` 283 | 284 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | buildscript { 3 | ext.kotlin_version = "1.3.72" 4 | repositories { 5 | google() 6 | jcenter() 7 | } 8 | dependencies { 9 | classpath 'com.android.tools.build:gradle:4.0.2' 10 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" 11 | classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1' 12 | // NOTE: Do not place your application dependencies here; they belong 13 | // in the individual module build.gradle files 14 | } 15 | } 16 | 17 | allprojects { 18 | repositories { 19 | google() 20 | jcenter() 21 | maven { url "https://jitpack.io" } 22 | } 23 | } 24 | 25 | task clean(type: Delete) { 26 | delete rootProject.buildDir 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=-Xmx2048m 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 -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AManCallJiang/AwesomeDownloader-Android/bade9da016acf5eabff270cece95533bf01387b1/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Fri Sep 11 14:34:15 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-6.1.1-all.zip 7 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /local.properties: -------------------------------------------------------------------------------- 1 | ## This file must *NOT* be checked into Version Control Systems, 2 | # as it contains information specific to your local configuration. 3 | # 4 | # Location of the SDK. This is only used by Gradle. 5 | # For customization when using a Version Control System, please read the 6 | # header note. 7 | #Sat Sep 26 22:08:16 CST 2020 8 | sdk.dir=D\:\\Android_SDK 9 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':AwesomeDownloader' 2 | include ':app' 3 | rootProject.name = "AwesomeDownloaderDemo" --------------------------------------------------------------------------------