1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package com.flightfeather.taizhang.common.utils.download
 
import android.content.Context
import cn.flightfeather.thirdappmodule.common.net.NetWorkProgressListener
import cn.flightfeather.thirdappmodule.util.file.FileUtils
import com.liulishuo.okdownload.DownloadTask
import com.liulishuo.okdownload.core.cause.EndCause.*
import com.liulishuo.okdownload.kotlin.execute1
import org.jetbrains.anko.doAsync
import java.io.File
 
/**
 * @author riku
 * Date: 2020/3/6
 */
object UpDownloadUtil {
 
    /**
     * @param onSuccess 下载完成后的文件路径
     */
    fun download(
        context: Context?, url: String, fileName: String,
        onSuccess: (downloadFilePath: String) -> Unit,
        onFailure: () -> Unit,
        netWorkProgressListener: NetWorkProgressListener? = null
    ) {
        context?.let {
            val parentFile = FileUtils.getCacheDir(it)
            val downloadFilePath = parentFile.path + File.separator + fileName
            val task = DownloadTask.Builder(url, parentFile)
                .setFilename(fileName)
                .setMinIntervalMillisCallbackProcess(16)
                .setPassIfAlreadyCompleted(false)
                .build()
            doAsync {
                task?.execute1(
                    connected = { task, blockCount, currentOffset, totalLength ->
                    },
                    progress = { task, currentOffset, totalLength ->
                        netWorkProgressListener?.onProgress(currentOffset, totalLength)
                    }
                ) { task, cause, realCause, model ->
                    task.tag = null
                    when (cause) {
                        COMPLETED -> {
                            onSuccess(downloadFilePath)
                        }
                        ERROR,
                        CANCELED,
                        FILE_BUSY,
                        SAME_TASK_BUSY,
                        PRE_ALLOCATE_FAILED -> {
                            onFailure()
                        }
                    }
                }
            }
        }
    }
}