Files
yusheng-android/MainModule/src/main/java/com/xscm/modulemain/utils/CountdownTimer.kt

45 lines
1.2 KiB
Kotlin
Raw Normal View History

2025-11-28 19:04:18 +08:00
package com.xscm.modulemain.utils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
class CountdownTimer {
private var job: Job? = null
private val _timeLeft = MutableStateFlow(0L)
val timeLeft: StateFlow<Long> = _timeLeft
fun startCountdown(endTimestamp: Long, scope: CoroutineScope) {
job?.cancel()
job = scope.launch {
while (true) {
val currentTime = System.currentTimeMillis() / 1000
val remainingTime = (endTimestamp - currentTime) * 1000 // 转换为毫秒
if (remainingTime <= 0) {
_timeLeft.value = 0
break
}
_timeLeft.value = remainingTime
delay(1000)
}
}
}
fun stop() {
job?.cancel()
}
fun formatTime(milliseconds: Long): String {
val seconds = (milliseconds / 1000).toInt()
val minutes = seconds / 60
val remainingSeconds = seconds % 60
return String.format("%02d:%02d", minutes, remainingSeconds)
}
}