83 lines
2.2 KiB
Kotlin
83 lines
2.2 KiB
Kotlin
package com.wyattjmiller.exam2
|
|
|
|
import android.os.SystemClock
|
|
import kotlin.math.max
|
|
import kotlin.math.min
|
|
|
|
class Timer {
|
|
private var mTargetTime: Long = 0
|
|
private var mTimeLeft: Long = 0
|
|
var isRunning = false
|
|
private set
|
|
private var mDurationMillis: Long = 0
|
|
|
|
fun start(millisLeft: Long) {
|
|
mDurationMillis = millisLeft
|
|
mTargetTime = SystemClock.uptimeMillis() + mDurationMillis
|
|
isRunning = true
|
|
}
|
|
|
|
fun start(hours: Int, minutes: Int, seconds: Int) {
|
|
// Add 1 sec to duration so timer stays on current second longer
|
|
mDurationMillis = (hours * 60 * 60 + minutes * 60 + seconds + 1) * 1000.toLong()
|
|
mTargetTime = SystemClock.uptimeMillis() + mDurationMillis
|
|
isRunning = true
|
|
}
|
|
|
|
fun stop() {
|
|
isRunning = false
|
|
}
|
|
|
|
fun pause() {
|
|
mTimeLeft = mTargetTime - SystemClock.uptimeMillis()
|
|
isRunning = false
|
|
}
|
|
|
|
fun resume() {
|
|
mTargetTime = SystemClock.uptimeMillis() + mTimeLeft
|
|
isRunning = true
|
|
}
|
|
|
|
val remainingMilliseconds: Long
|
|
get() = if (isRunning) {
|
|
max(0, mTargetTime - SystemClock.uptimeMillis())
|
|
} else 0
|
|
|
|
private val remainingSeconds: Int
|
|
get() {
|
|
return if (isRunning) {
|
|
((remainingMilliseconds / 1000) % 60).toInt()
|
|
} else 0
|
|
}
|
|
|
|
private val remainingMinutes: Int
|
|
get() {
|
|
return if (isRunning) {
|
|
(((remainingMilliseconds / 1000) / 60) % 60).toInt()
|
|
} else 0
|
|
}
|
|
|
|
private val remainingHours: Int
|
|
get() {
|
|
return if (isRunning) {
|
|
(((remainingMilliseconds / 1000) / 60) / 60).toInt()
|
|
} else 0
|
|
}
|
|
|
|
val progressPercent: Int
|
|
get() {
|
|
return if (mDurationMillis != 1000L) {
|
|
min(
|
|
100, 100 - ((remainingMilliseconds - 1000) * 100 /
|
|
(mDurationMillis - 1000)).toInt()
|
|
)
|
|
} else 0
|
|
}
|
|
|
|
override fun toString(): String {
|
|
return String.format(
|
|
"%02d:%02d:%02d", remainingHours,
|
|
remainingMinutes, remainingSeconds
|
|
)
|
|
}
|
|
} |