properly handle stopwatch pause/resume

This commit is contained in:
tibbi 2018-03-07 22:11:02 +01:00
parent 422cbf4378
commit caef58df54
1 changed files with 11 additions and 6 deletions

View File

@ -24,7 +24,8 @@ class StopwatchFragment : Fragment() {
private val updateHandler = Handler()
private val mainLooper = Looper.getMainLooper()
private var uptimeAtStart = 0L
private var ticksCount = 0
private var totalTicks = 0
private var currentTicks = 0 // ticks that reset at pause
private var isRunning = false
lateinit var view: ViewGroup
@ -89,26 +90,30 @@ class StopwatchFragment : Fragment() {
updateHandler.post(updateRunnable)
uptimeAtStart = SystemClock.uptimeMillis()
} else {
val totalDuration = SystemClock.uptimeMillis() - uptimeAtStart
val prevSessionsMS = (totalTicks - currentTicks) * UPDATE_INTERVAL
val totalDuration = SystemClock.uptimeMillis() - uptimeAtStart + prevSessionsMS
updateHandler.removeCallbacksAndMessages(null)
view.stopwatch_time.text = totalDuration.formatStopwatchTime(true)
currentTicks = 0
totalTicks--
}
}
private fun updateDisplayedText() {
view.stopwatch_time.text = (ticksCount * UPDATE_INTERVAL).formatStopwatchTime(false)
view.stopwatch_time.text = (totalTicks * UPDATE_INTERVAL).formatStopwatchTime(false)
}
private val updateRunnable = object : Runnable {
override fun run() {
if (isRunning) {
ticksCount++
updateHandler.postAtTime(this, uptimeAtStart + ticksCount * UPDATE_INTERVAL)
if (ticksCount % 10 == 0) {
if (totalTicks % 10 == 0) {
mainLooper.run {
updateDisplayedText()
}
}
totalTicks++
currentTicks++
updateHandler.postAtTime(this, uptimeAtStart + currentTicks * UPDATE_INTERVAL)
}
}
}