Commit 45007791 authored by wanglei's avatar wanglei

...

parent 8b166a72
......@@ -27,6 +27,7 @@ import java.io.File
import kotlin.math.abs
@Suppress("ControlFlowWithEmptyBody")
class DownloadAdapter : BaseQuickAdapter<DownloadBean, DownloadAdapter.DownloadViewHolder>() {
private val TAG = "DownloadAdapter"
......@@ -37,20 +38,83 @@ class DownloadAdapter : BaseQuickAdapter<DownloadBean, DownloadAdapter.DownloadV
var moreAction: ((archView: View, item: DownloadBean) -> Unit)? = null
override fun onBindViewHolder(holder: DownloadViewHolder, position: Int, item: DownloadBean?) {
if (item == null) return
when {
item.isTime -> {
val binding = ItemDownloadTimeBinding.bind(holder.itemView)
binding.tvTime.text = item.time.toFormatTime()
}
item.uiType == 1 -> {
bindType1(holder, position, item, null)
}
item.uiType == 2 -> {
bindType2(holder, position, item, null)
}
}
}
override fun onBindViewHolder(holder: DownloadViewHolder, position: Int, item: DownloadBean?, payloads: List<Any>) {
if (item == null) return
val context = holder.itemView.context
if (item.isTime) {
when {
item.isTime -> {
val binding = ItemDownloadTimeBinding.bind(holder.itemView)
binding.tvTime.text = item.time.toFormatTime()
} else if (item.uiType == 1) {
}
item.uiType == 1 -> {
bindType1(holder, position, item, payloads)
}
item.uiType == 2 -> {
bindType2(holder, position, item, payloads)
}
}
}
private fun bindType1(holder: DownloadViewHolder, position: Int, item: DownloadBean, payloads: List<Any>?) {
val binding = ItemDownloadBinding.bind(holder.itemView)
if (payloads.isNullOrEmpty()) {
val file = File(item.path)
Glide.with(context).load(file.absoluteFile).centerCrop().into(binding.iv)
Glide.with(context).load(item.url).centerCrop().into(binding.iv)
binding.tvName.text = file.name
binding.tvSize.text = file.length().toFormatSize()
when (item.status) {
FileDownloadStatus.completed -> {
binding.flMore.visibility = View.VISIBLE
binding.flDownload.visibility = View.GONE
}
FileDownloadStatus.paused -> {
binding.flMore.visibility = View.GONE
binding.flDownload.visibility = View.VISIBLE
binding.circularProgressBar.progress = item.progress.toFloat()
}
FileDownloadStatus.progress -> {
binding.flMore.visibility = View.GONE
binding.flDownload.visibility = View.VISIBLE
binding.circularProgressBar.progress = item.progress.toFloat()
replaceListener(item, position)
}
}
binding.flDownload.setOnClickListener {
pauseResumeDownload(item, position)
}
binding.flMore.setOnClickListener {
moreAction?.invoke(it, item)
}
} else {
when (item.status) {
FileDownloadStatus.completed -> {
binding.flMore.visibility = View.VISIBLE
......@@ -67,15 +131,17 @@ class DownloadAdapter : BaseQuickAdapter<DownloadBean, DownloadAdapter.DownloadV
binding.flMore.visibility = View.GONE
binding.flDownload.visibility = View.VISIBLE
binding.circularProgressBar.progress = item.progress.toFloat()
replaceListener(item)
replaceListener(item, position)
}
}
binding.flDownload.setOnClickListener {
pauseResumeDownload(item)
super.onBindViewHolder(holder, position, item, payloads)
}
}
} else if (item.uiType == 2) {
private fun bindType2(holder: DownloadViewHolder, position: Int, item: DownloadBean, payloads: List<Any>?) {
val binding = ItemDownloadCardBinding.bind(holder.itemView)
if (payloads.isNullOrEmpty()) {
Glide.with(context).load(item.url).centerCrop().into(binding.iv)
binding.tvName.text = item.name.ifEmpty { item.url.split("/").last() }
binding.tvSize.text = item.size.toFormatSize()
......@@ -99,7 +165,7 @@ class DownloadAdapter : BaseQuickAdapter<DownloadBean, DownloadAdapter.DownloadV
FileDownloadStatus.progress -> {
binding.ivXiazaiZantin.setImageResource(R.mipmap.xiazhaiz_download)
binding.circularProgressBar.progress = item.progress.toFloat()
replaceListener(item)
replaceListener(item, position)
}
FileDownloadStatus.completed -> {
......@@ -115,17 +181,49 @@ class DownloadAdapter : BaseQuickAdapter<DownloadBean, DownloadAdapter.DownloadV
binding.ivDownload.setOnClickListener {
downloadAction?.invoke()
context.showDownloadConfirmDialog(item) {
downloadItem(context, item)
downloadItem(context, item, position)
}
}
binding.flDownload.setOnClickListener {
pauseResumeDownload(item)
pauseResumeDownload(item, position)
}
} else {
var status = item.status
// LogEx.logDebug(TAG, "status=${item.status} path=${item.path} progress=${item.progress}")
if (item.progress == 100) {
status = FileDownloadStatus.completed
}
binding.ivDownload.isVisible = status == FileDownloadStatus.pending
binding.flDownload.isVisible = !binding.ivDownload.isVisible
binding.ivFinish.isVisible = false
when (status) {
FileDownloadStatus.paused -> {
binding.ivXiazaiZantin.setImageResource(R.mipmap.zanting_download)
binding.circularProgressBar.progress = item.progress.toFloat()
}
FileDownloadStatus.progress -> {
binding.ivXiazaiZantin.setImageResource(R.mipmap.xiazhaiz_download)
binding.circularProgressBar.progress = item.progress.toFloat()
replaceListener(item, position)
}
FileDownloadStatus.completed -> {
binding.flDownload.isVisible = false
binding.ivFinish.isVisible = true
}
private fun pauseResumeDownload(item: DownloadBean) {
else -> {
}
}
}
}
private fun pauseResumeDownload(item: DownloadBean, position: Int) {
if (item.status == FileDownloadStatus.progress) {
FileDownloader.getImpl().pause(item.downloadId)
LogEx.logDebug(TAG, "pause downloadId=${item.downloadId}")
......@@ -133,7 +231,7 @@ class DownloadAdapter : BaseQuickAdapter<DownloadBean, DownloadAdapter.DownloadV
}
if (item.status == FileDownloadStatus.paused) {
downloadItem(context, item)
downloadItem(context, item, position)
LogEx.logDebug(TAG, "start")
return
}
......@@ -157,11 +255,11 @@ class DownloadAdapter : BaseQuickAdapter<DownloadBean, DownloadAdapter.DownloadV
}
@SuppressLint("NotifyDataSetChanged")
fun downloadItem(context: Context, item: DownloadBean) {
fun downloadItem(context: Context, item: DownloadBean, position: Int) {
item.path = context.getDownloadPath(item.url, item.name)
item.path = context.getDownloadPath(item)
item.fileDownloadListener = createNewLister(item, "downloadItem")
item.fileDownloadListener = createNewLister(item, "downloadItem", position)
val downloadTask = FileDownloader.getImpl().create(item.url)
.setPath(item.path)
......@@ -171,44 +269,41 @@ class DownloadAdapter : BaseQuickAdapter<DownloadBean, DownloadAdapter.DownloadV
item.downloadId = downloadTask.id
}
private fun replaceListener(item: DownloadBean) {
private fun replaceListener(item: DownloadBean, position: Int) {
if (item.fileDownloadListener == null) {
item.fileDownloadListener = createNewLister(item, "replaceListener")
item.fileDownloadListener = createNewLister(item, "replaceListener", position)
FileDownloader.getImpl().replaceListener(item.downloadId, item.fileDownloadListener)
}
}
private fun createNewLister(item: DownloadBean, tag: String = ""): FileDownloadListener {
private fun createNewLister(item: DownloadBean, tag: String = "", position: Int): FileDownloadListener {
return object : FileDownloadListener() {
override fun pending(task: BaseDownloadTask?, soFarBytes: Int, totalBytes: Int) {
}
@SuppressLint("NotifyDataSetChanged")
override fun progress(task: BaseDownloadTask?, soFarBytes: Int, totalBytes: Int) {
val percent = soFarBytes * 100 / totalBytes
LogEx.logDebug(TAG, "progress tag=$tag item=${item.downloadId} percent=$percent")
LogEx.logDebug(TAG, "progress tag=$tag item=${item.downloadId} percent=$percent ${item.path}")
if (percent < 0) return
item.progress = percent
item.status = FileDownloader.getImpl().getStatus(item.url, item.path)
notifyDataSetChanged()
notifyItemChanged(position, "aaa")
}
@SuppressLint("NotifyDataSetChanged")
override fun completed(task: BaseDownloadTask?) {
item.progress = 100
item.status = FileDownloader.getImpl().getStatus(item.url, item.path)
item.time = System.currentTimeMillis()
notifyDataSetChanged()
notifyItemChanged(position, "aaa")
}
@SuppressLint("NotifyDataSetChanged")
override fun paused(task: BaseDownloadTask?, soFarBytes: Int, totalBytes: Int) {
LogEx.logDebug(TAG, "paused tag=$tag item=${item.downloadId}")
val percent = soFarBytes * 100 / totalBytes
item.progress = abs(percent)
item.status = FileDownloadStatus.paused
notifyDataSetChanged()
notifyItemChanged(position, "aaa")
}
override fun error(task: BaseDownloadTask?, e: Throwable?) {
......
......@@ -15,11 +15,14 @@ import com.base.browserwhite.ui.views.DialogViews.showMediaMoreDialog
import com.base.browserwhite.utils.BarUtils
import com.base.browserwhite.utils.DownloadHelper.getDownloadJson
import com.base.browserwhite.utils.DownloadHelper.getDownloadJsonBean
import com.base.browserwhite.utils.DownloadHelper.saveDownloadRecordFile
import com.base.browserwhite.utils.IntentEx.shareAction
import com.base.browserwhite.utils.KotlinExt.toFormatTime
import com.base.browserwhite.utils.PermissionHelp.checkStorePermission
import com.base.browserwhite.utils.PermissionHelp.requestStorePermission
import com.google.gson.Gson
import com.liulishuo.filedownloader.FileDownloader
import com.liulishuo.filedownloader.model.FileDownloadStatus
import java.io.File
class WebDownloadManagerActivity : BaseActivity<ActivityWebDownloadManagerBinding>() {
......@@ -53,6 +56,7 @@ class WebDownloadManagerActivity : BaseActivity<ActivityWebDownloadManagerBindin
}
binding.llEmpty.isVisible = adapter.items.isEmpty()
}
}
},
shareAction = {
......@@ -103,6 +107,9 @@ class WebDownloadManagerActivity : BaseActivity<ActivityWebDownloadManagerBindin
binding.llEmpty.isVisible = true
} else {
val beanList = arrayListOf<DownloadBean>()
beanList.forEach {
it.status = FileDownloader.getImpl().getStatus(it.downloadId, it.path)
}
val timeList = arrayListOf<String>()
list.sortedBy { it.time }.forEach { old ->
......@@ -117,4 +124,13 @@ class WebDownloadManagerActivity : BaseActivity<ActivityWebDownloadManagerBindin
}
}
override fun onPause() {
super.onPause()
}
override fun onDestroy() {
super.onDestroy()
this.saveDownloadRecordFile(adapter.items)
}
}
\ No newline at end of file
......@@ -17,16 +17,15 @@ import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.lifecycle.lifecycleScope
import com.base.browserwhite.bean.DownloadBean
import com.base.browserwhite.bean.downloadBeanGson
import com.base.browserwhite.databinding.FragmentWebViewBinding
import com.base.browserwhite.ui.activity.download.DownloadAdapter
import com.base.browserwhite.ui.fragment.BaseFragment
import com.base.browserwhite.ui.views.DownloadDialog.showDownloadVideoDialog
import com.base.browserwhite.utils.DownloadHelper.getDownloadJson
import com.base.browserwhite.utils.DownloadHelper.getDownloadJsonBean
import com.base.browserwhite.utils.DownloadHelper.saveDownloadRecordFile
import com.base.browserwhite.utils.LogEx
import com.google.gson.Gson
import com.liulishuo.filedownloader.model.FileDownloadStatus
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
......@@ -89,7 +88,7 @@ class WebViewFragment : BaseFragment<FragmentWebViewBinding>() {
requireContext().showDownloadVideoDialog(
adapter, downloadList,
dismissAction = {
saveDownloadRecordFile(downloadList)
requireContext().saveDownloadRecordFile(downloadList)
},
)
}
......@@ -98,38 +97,6 @@ class WebViewFragment : BaseFragment<FragmentWebViewBinding>() {
}
private fun saveDownloadRecordFile(downloadList: ArrayList<DownloadBean>) = lifecycleScope.launch(Dispatchers.IO) {
val recordFile = requireContext().getDownloadJson()
//已开始的任务
val startedList = downloadList.filter {
it.status == FileDownloadStatus.progress ||
it.status == FileDownloadStatus.paused
}
startedList.forEach { it.time = System.currentTimeMillis() }
//完成的任务
val finishList = downloadList.filter { it.status == FileDownloadStatus.completed }
//以前的去除重叠的
val olderList =
getDownloadJsonBean(recordFile, downloadBeanGson).filter { !startedList.contains(it) || !startedList.contains(it) }
val arrayList = arrayListOf<DownloadBean>()
arrayList.addAll(olderList)
arrayList.addAll(startedList)
arrayList.addAll(finishList)
arrayList.forEach {
LogEx.logDebug(TAG, "saveDownloadRecordFile ${it.name} ${it.downloadId} ${it.status} ")
}
val json = downloadBeanGson.toJson(arrayList)
recordFile.writeText(json)
}
private fun reloadWebView() {
binding.llError.visibility = View.GONE
binding.webView.visibility = View.VISIBLE
......@@ -406,7 +373,7 @@ class WebViewFragment : BaseFragment<FragmentWebViewBinding>() {
override fun onDestroy() {
super.onDestroy()
saveDownloadRecordFile(downloadList)
requireContext().saveDownloadRecordFile(downloadList)
}
}
\ No newline at end of file
......@@ -2,16 +2,19 @@ package com.base.browserwhite.utils
import android.content.Context
import android.os.Environment
import androidx.lifecycle.lifecycleScope
import com.base.browserwhite.R
import com.base.browserwhite.bean.DownloadBean
import com.base.browserwhite.bean.downloadBeanGson
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.liulishuo.filedownloader.model.FileDownloadStatus
import java.io.File
import java.lang.reflect.Type
object DownloadHelper {
private val TAG = "DownloadHelper"
fun Context.getDownloadJson(): File {
val file = File(this.filesDir, "downloadRecord")
val recordFile = File(file, "download.json")
......@@ -27,24 +30,29 @@ object DownloadHelper {
fun getDownloadJsonBean(recordFile: File, gson: Gson = downloadBeanGson): List<DownloadBean> {
val olderText = recordFile.readText()
val type: Type = object : TypeToken<List<DownloadBean>>() {}.type
return gson.fromJson<List<DownloadBean>?>(olderText, type)?: listOf()
return gson.fromJson<List<DownloadBean>?>(olderText, type) ?: listOf()
}
fun Context.getDownloadPath(
url: String,
name: String,
item: DownloadBean
): String {
var fileName = url.split("/").last()
if (name.isNotEmpty()) {
fileName = name
}
// 设置下载文件的存储位置
val dirPath = File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), resources.getString(R.string.app_name)
).absolutePath
var path = "$dirPath/$fileName"
if (item.status == FileDownloadStatus.paused) {
return "$dirPath/${item.name}"
}
var fileName = item.url.split("/").last()
if (item.name.isNotEmpty()) {
fileName = item.name
}
var path = "$dirPath/$fileName"
while (File(path).exists()) {
val split = File(path).name.split(".")
val suffix = split[1]
......@@ -57,10 +65,47 @@ object DownloadHelper {
cname += "1"
}
path = "$dirPath/$cname.$suffix"
item.name = "$cname.$suffix"
LogEx.logDebug("getDownloadPath", "path=$path")
}
return path
}
fun Context.saveDownloadRecordFile(downloadList: List<DownloadBean>) = Thread {
val recordFile = getDownloadJson()
//已开始的任务
val startedList = downloadList.filter {
it.status == FileDownloadStatus.progress ||
it.status == FileDownloadStatus.paused
}
startedList.forEach { it.time = System.currentTimeMillis() }
val startPath = startedList.map { it.path }
//完成的任务
val finishList = downloadList.filter { it.status == FileDownloadStatus.completed }
val finishPath = finishList.map { it.path }
//以前的去除重叠的
val olderList = getDownloadJsonBean(recordFile, downloadBeanGson).toMutableList()
olderList.removeIf { startPath.contains(it.path) }
olderList.removeIf { finishPath.contains(it.path) }
val arrayList = arrayListOf<DownloadBean>()
arrayList.addAll(olderList)
arrayList.addAll(startedList)
arrayList.addAll(finishList)
arrayList.forEach {
LogEx.logDebug(TAG, "saveDownloadRecordFile ${it.name} ${it.downloadId} ${it.status} ${it.path}")
}
val json = downloadBeanGson.toJson(arrayList)
recordFile.writeText(json)
}.start()
}
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="internal_files" path="." />
<files-path
name="internal_files"
path="." />
<external-path
name="download_path"
path="Download/" />
</paths>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment