package com.flightfeather.taizhang.common.utils.download
|
|
import android.content.Context
|
import cn.flightfeather.thirdapp.common.net.NetWorkProgressListener
|
import cn.flightfeather.thirdapp.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()
|
}
|
}
|
}
|
}
|
}
|
}
|
}
|