0
votes

I am using countDownTimer in my code. The problem is, countdowntimer is not accurate. The onTick method will not always execute every second, it can be a few milliseconds off. This becomes an issue when trying to execute a certain task based on millisUntilFinished. I am trying to log when ten seconds of my 20 second timer has passed:

Here is the relevant code:

    if (millisUntilFinished == 10000) { //TEN SECONDS

                Log.v(TAG, "TEN SECONDS LEFT");
            }

The issue arises here, as countDownTimer may never even have millisUntilFinished == 10000, it may equal 1001 and so my code will not execute. Is there anyway to somehow round the millisUntilFinished (which is a long) to the nearest thousands? I have tried the following:

 millisUntilFinishedRounded = MathUtils.round((double) millisUntilFinished, -3); // nearest thousand, 2000.0

but I cannot resolve 'MathUtils'

I am lost. I would really appreciate any feedback (positive or negative)! Thank you so much for all of your help.

{Rich}
1
((500 + millisUntilFinished) / 1000) * 1000 rounds a positive value to the nearest 1000. But you could use (millisUntilFinished >= 9500 && millisUntilFinished < 10500) as your condition alternatively. - Andy Turner
Or if you want to execute some code one time. Just check if millisUntilFinished < 10000 and then a set a boolean to say the code was executed so it doesn't run next time. - Adam W
@AndyTurner Thanks for your time, why are we adding 500? - Ruchir Baronia
You need to add 500 if you want to round to the nearest 1000, as opposed to rounding down to the nearest 1000. e.g. for 750: (750 + 500) / 1000 * 1000 = 1000, whereas 750 / 1000 * 1000 = 0. - Andy Turner
@AndyTurner Your answer is working! I am a little bit confused why though... Isn't 900/1000 = 0.9? 0.9 x 1000 = 9000, not 10000; why does this still work though? Is it rounding up from 0.9 -> 1? If so, how would it work if the quotient was above one but below 2, would it still round up again, to two? thanks so much for the answer, I will mark it as best answer and like your post as soon as these questions are answered! :) - Ruchir Baronia

1 Answers

1
votes

There are a few alternatives:

  1. You can round a positive integer to the nearest N by adding N/2, dividing by N and multiplying by N again:

    ((500 + millisUntilFinished) / 1000) * 1000

  2. You can use a condition which just checks if the value is in the range which would be rounded to 10000:

    millisUntilFinished >= 9500 && millisUntilFinished < 10500

  3. You can check for the first time that millisUntilFinished drops below 10000:

    boolean printedMessage = false;
    while (true) {
      millisUntilFinished = ...
      if (!printedMessage && millisUntilFinished < 10000) {
        System.out.println("Your message");
        printedMessage = true;
      }
    }