I have a CountDownTimer that runs fine most times. However, it at times begins to flicker in the TextView displaying the countdown. I have it displayed like so:
HH:MM:SS
As it's counting down the last second will jump from for example 9 to 7 to 8 in one second. And then the next second it will quickly flicker from 8 to 6 to 7.
I have tried passing the variable millisUntilFinished directly to the method updating the textView, but the issue persists. Note that I'm saving the countdown and continuing it during onStop and onStart methods.
private fun startVisibleCountdown() {
visibleCountdownRunning = true
object : CountDownTimer(timeLeftInMillisecondsVisibleCounter, 1000) {
override fun onTick(millisUntilFinished: Long) {
timeLeftInMillisecondsVisibleCounter = millisUntilFinished
updateCountDownTextVisible()
}
override fun onFinish() {
//not relevant here
}
}.start()
}
fun updateCountDownTextVisible() {
var seconds = (timeLeftInMillisecondsVisibleCounter / 1000).toInt()
val hours = seconds / (60 * 60)
val tempMint = seconds - hours * 60 * 60
val minutes = tempMint / 60
seconds = tempMint - (minutes * 60);
textViewTimer.text = (String.format("%02d", hours)
+ ":" + String.format("%02d", minutes)
+ ":" + String.format("%02d", seconds))
}
Saving and returning to countdown when app is closed:
override fun onStop() {
super.onStop()
if (visibleCountdownRunning) {
timeLeftInMillisecondsVisibleCounter += System.currentTimeMillis()
}
val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE) ?: return
with (sharedPref.edit()) {
putLong(timeLeftVisibleCounterKey, timeLeftInMillisecondsVisibleCounter)
putBoolean(visibleCountdownRunningKey, visibleCountdownRunning)
apply()
}
}
override fun onStart() {
super.onStart()
val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE) ?: return
timeLeftInMillisecondsVisibleCounter = sharedPref.getLong(timeLeftVisibleCounterKey, 43200000)
visibleCountdownRunning = sharedPref.getBoolean(visibleCountdownRunningKey, false)
if (visibleCountdownRunning) {
timeLeftInMillisecondsVisibleCounter -= System.currentTimeMillis()
if (timeLeftInMillisecondsVisibleCounter > 0) {
startVisibleCountdown()
} else {
timeLeftInMillisecondsVisibleCounter = 43200000
visibleCountdownRunning = false
}
}
}