签约 A
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user