0

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
        }
    }
}
3
  • Do you call the startVisibleCountdown() function also somewhere else in your whole code?
    – Ma3x
    Commented Dec 7, 2021 at 19:05
  • Yeah, sorry it's just a button click to start it in OnCreateView. Want me to add the code for it? Commented Dec 7, 2021 at 19:48
  • See if my answer helps, if not, please provide that part of the code as well.
    – Ma3x
    Commented Dec 7, 2021 at 20:04

3 Answers 3

2

Every time onStart fires (e.g. by going to the home screen then back into the app) if the current timer still has time left, you start another one through that startVisibleCountdown() call. You haven't shown you're stopping the old one anywhere - your code isn't even keeping a reference to it, it's just started anonymously, and runs until it completes (or the app is killed)

If you have multiple timers running, they all set timeLeft according to the value passed into their onTick, and then they call the function that displays that. Since their updates are all getting posted to the message queue, it's possible there's a slight timing discrepancy between them (e.g. one has millisUntilFinished = 6000 and one has 5999) and you're getting them out of order.

That would explain why it's changing at all (you have multiple timers setting the text on the TextView when there should only be one) and why it's going backwards (no hard guarantees about which message is at the front of the queue or even when it arrives exactly)

So you need to make sure you're only ever running one instance of your timer - there are a few ways to handle that, this is probably the safest approach (not thread-safe but that's not an issue with what you're doing here):

private var myTimer: CountdownTimer? = null

...

fun startVisibleCountdown() {
    // enforce a single current timer instance
    if (myTimer != null) return
    myTimer = object : CountDownTimer(timeLeftInMillisecondsVisibleCounter, 1000) {
        ...
        override fun onFinish() {
            // if a timer finishes (i.e. it isn't cancelled) clear it so another can be started
            myTimer = null
        }
    }
}

...

override fun onStop() {
    ...
    // probably better in a function called stopVisibleCountdown() for symmetry and centralising logic
    myTimer?.run { cancel() }
    myTimer = null
}

That way, there's only one place you're actually creating and starting a timer, and that code ensures only one instance is running at a time. That instance is only cleared when the timer successfully finishes, or when it's explicitly stopped. By centralising it like this (and putting all your defensive coding in one place) you can call the start function from multiple places (onStart, some button's onClick) and it will all be handled safely

5
  • I appreciate the efforts but this isn't the case. OnStart only sets it to a negative value IF the countdown has continued past 0. Yes, I do subtract a large number in OnStart. But if you notice I add that same number on OnStop. That's how I keep a track of the countdown while the app is closed by using system time. The countdown doesn't continue to run after onStop. I also checked with Log that the timer isn't started multiple times. Commented Dec 8, 2021 at 14:42
  • 1
    Oh I see what you're doing in onStop, my bad (and that's a pretty good solution). But in that case, if it's correctly keeping track of the time remaining, then you're sometimes calling startVisibleCountdown() in onStart - that creates a new timer instance. How are you stopping the old one? Your code isn't keeping a reference to it Commented Dec 8, 2021 at 17:27
  • 1
    I put more info in the answer since there's no room in here to explain the effects! Commented Dec 8, 2021 at 17:47
  • Thank you, and indeed canceling the timer in my OnStop method solved the problem. I made some edits to cut out the fluff and make it a good resource that solves the problem. Hope you don't mind. Commented Dec 15, 2021 at 15:43
  • @TheFluffyTRex no worries - I tweaked the solution code to be what I'd consider safer, enforcing a single instance through the start function. It's not really an issue for what you're doing (or what you've posted at least) but I think it's good practice to be defensive and enforce valid behaviour, and as a general approach it's what I'd recommend I think! Commented Dec 15, 2021 at 19:24
0

Try this, its working with me but its java, convert it to Kotlin and it will work with you

    long time = 20 *60;
       new CountDownTimer( time * 1000, 1000) {

        @SuppressLint("SetTextI18n")
        public void onTick(long millisUntilFinished) {
            String timeremaining = TimetoString(millisUntilFinished);
            // update your textview here 
        }

        public void onFinish() {
        // here when the counter finish 
      
        }
    }.start();
3
  • You're not supposed to do time * 1000 in the Countdown timer. Why are you doing that? Commented Dec 7, 2021 at 18:34
  • because its millseconds, every 1000 mille = 1 sec @TheFluffyTRex Commented Dec 9, 2021 at 10:54
  • @TheFluffyTRex .. Commented Dec 12, 2021 at 10:45
0

Since you are calling your startVisibleCountdown() function both from onStart() and when a button is clicked, it is likely that you have 2 CountDownTimer objects running and calling your updateCountDownTextVisible() code at the same time. This could explain the flickering and skipping seconds in a weird way.

Keep in mind, that even if you comment out the call to startVisibleCountdown() inside your onStart() function, Android sometimes does not prevent multi clicks from going through (depends on what type of button you are using and how did you wire up your onClickListener), so you might also be starting multiple countdown timers when clicking the button.

Add some log output (Log.d(...)) in you startVisibleCountdown(), just to make sure that it is not being called multiple times.

EDIT: Since you checked that your click handlers are not called multiple times, then this means that you are not stopping your countdown anywhere in your code when your activity/fragment lifecycle stops and restarts (we can only see your onStop and onStart methods, but you don't stop the countdown there).

This means that the timer keeps running in the background even after onStop is called. So when the onStart is called again it will start another timer, and depending on the timing (this is why it is a bit random), you might see the seconds "skipping" up and then down again.

So my advice would still be the same as before. Add some log output in your startVisibleCountdown(), just to make sure that it is not being called multiple times. Reproduce the flickering behavior and observe the log. It will have multiple calls to startVisibleCountdown() in it.

You can just start the countdown, put the app in the background, wait for a second, and reopen it. Repeat a few times if it does not work the first time since it depends on timing.

To solve this problem, stop your countdown timer in the onStop() method.

// to keep the reference to the CountDownTimer
private var countDown: CountDownTimer? = null

override fun onStop() {
    // ...
    countDown?.cancel()
    countDown = null
    // ...
}

private fun startVisibleCountdown() {
    //...
    countDown = object : CountDownTimer(timeLeftInMillisecondsVisibleCounter, 1000) {
        // ...
    }
    countDown.start()
}
3
  • Nope. This isn't the case. I checked with Log. It makes no sense for a countdown to start without me clicking a button when I use the onClick method. The scenario you're describing means code inside an OnClick method would be called even if I did not press the button. Commented Dec 8, 2021 at 14:44
  • I describe a scenario where after you click the button the code inside the OnClick method would be called multiple times. I never said that OnClick would be called without you interacting with the button. But if you confirmed that you do not have 2 countdowns running at the same time at any point in time, then you will have to provide all the code that is run when you click the button, for others to be able to help. Can you please also include the Log line when you update the question.
    – Ma3x
    Commented Dec 8, 2021 at 15:20
  • @TheFluffyTRex see my edit
    – Ma3x
    Commented Dec 8, 2021 at 16:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.