1:修改手机换绑倒计时添加管理类

This commit is contained in:
2025-12-19 18:41:29 +08:00
parent 5c607c58ae
commit 6bd210217a
3 changed files with 165 additions and 33 deletions

View File

@@ -0,0 +1,114 @@
package com.xscm.modulemain.utils
import android.os.Handler
import android.os.Looper
/**
* 项目名称:羽声语音
* 时间2025/12/19 16:21
* 用途:
*/
class CountDownManager {
// 存储所有倒计时任务
private val timerMap = mutableMapOf<String, CountDownTask>()
// 单例模式
companion object {
private var instance: CountDownManager? = null
fun getInstance(): CountDownManager {
return instance ?: synchronized(this) {
instance ?: CountDownManager().also { instance = it }
}
}
}
data class CountDownTask(
val tag: String,
val totalSeconds: Long,
val interval: Long = 1000L,
var currentTime: Long = 0L,
var isRunning: Boolean = false,
val onTick: ((Long, String) -> Unit)? = null,
val onFinish: ((String) -> Unit)? = null
)
// 开始倒计时
fun startCountDown(
tag: String,
totalSeconds: Long,
interval: Long = 1000L,
onTick: ((Long, String) -> Unit)? = null,
onFinish: ((String) -> Unit)? = null
) {
// 如果已有相同tag的倒计时先取消
cancelCountDown(tag)
val task = CountDownTask(tag, totalSeconds, interval, totalSeconds, true, onTick, onFinish)
timerMap[tag] = task
val handler = Handler(Looper.getMainLooper())
val runnable = object : Runnable {
override fun run() {
val currentTask = timerMap[tag]
if (currentTask == null || !currentTask.isRunning) {
return
}
currentTask.currentTime -= 1
if (currentTask.currentTime > 0) {
onTick?.invoke(currentTask.currentTime, tag)
handler.postDelayed(this, interval)
} else {
currentTask.isRunning = false
timerMap.remove(tag)
onFinish?.invoke(tag)
}
}
}
handler.postDelayed(runnable, interval)
}
// 获取剩余时间
fun getRemainingTime(tag: String): Long {
return timerMap[tag]?.currentTime ?: 0L
}
// 检查是否在倒计时中
fun isCounting(tag: String): Boolean {
return timerMap[tag]?.isRunning ?: false
}
// 取消单个倒计时
fun cancelCountDown(tag: String) {
timerMap[tag]?.isRunning = false
timerMap.remove(tag)
}
// 取消所有倒计时
fun cancelAll() {
timerMap.values.forEach { it.isRunning = false }
timerMap.clear()
}
// 暂停倒计时(保存状态)
fun pauseCountDown(tag: String) {
timerMap[tag]?.isRunning = false
}
// 恢复倒计时
fun resumeCountDown(tag: String) {
val task = timerMap[tag] ?: return
if (task.currentTime > 0) {
startCountDown(
tag,
task.currentTime,
task.interval,
task.onTick,
task.onFinish
)
}
}
}