Reputation: 7561
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}
Upvotes: 0
Views: 335
Reputation: 140319
There are a few alternatives:
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
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
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;
}
}
Upvotes: 1