Issue
I have a CountDown timer that counts down from 10000ms to 0ms in increments of 1 second each to make a button clickable after 10 seconds. Although the timer is accurate and does what the code says, I would like to change the way the seconds are expressed but I don't know how.
java:
void startTimer() {
cTimer = new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
c.setText("Please wait " + millisUntilFinished/1000 + " seconds");
thx.setText(millisUntilFinished/1000 + "");
thx.setAlpha(.5f);
thx.setClickable(false);
}
public void onFinish() {
c.setText("done");
thx.setText("ready");
thx.setAlpha(1f);
thx.setClickable(true);
}
};
cTimer.start();
}
Outputted (Every second): 9, 8, 7, 6, 5, 4, 3, 2, 1, (still 1), ready
Desired: (Every second): 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, ready
Thanks,
B
EDIT:
I added 1 to the countdown, thx.setText(((millisUntilFinished/1000) + 1) + "");
New output: 10, 9, 8, 7, 6, 5, 4 ,3 , 2, (Still 2), ready
Closer... but not quite.
Solution
This is just my investigation on CountDownTimer when I used CountDownTimer few month before and its work fine in my application.
public void onTick(long millisUntilFinished)
This millisUntilFinished will give the remaining time in millisecond, and last 1000 millisecond is to call onFinish() method, So onTick method will get called until the remaining time is more than (1000(for OnFinish) + 1000(for counter)) milliseconds, if the last remaining millisecond is less than 2000millisecond it will skip the onTick() and it will directly call onFinish() when timer ends. For more details just see Handler method in this source.
So the main problem is when we give some X(our case 10000)milliseconds, but to start the counter it's taking some 50 to 150 milliseconds, So if we add that millisecond in our total time we will get the counter until end,
So you can try like this, Nothing change just I added 150 milliseconds in your total time.
void startTimer() {
cTimer = new CountDownTimer(10150, 1000) {
public void onTick(long millisUntilFinished) {
c.setText("Please wait " + millisUntilFinished/1000 + " seconds");
thx.setText(millisUntilFinished/1000 + "");
thx.setAlpha(.5f);
thx.setClickable(false);
}
public void onFinish() {
c.setText("done");
thx.setText("ready");
thx.setAlpha(1f);
thx.setClickable(true);
}
};
cTimer.start();
}
Let me know if its works or not, If you ask me why you are not using Handler, I can say CountDownTime internally using Handler.
Answered By - Muthukrishnan Rajendran
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.