Search code examples
javaandroid-studiocountdowntimerandroid-alarmsandroid-handler

Countdown timer display a toast half time


I'm trying to implement something like a countdown timer that Display a message half the minutes selected. For example if I set 6 minutes, when countdown timer reach 3 minutes , it displays a toast and then continue to tick.

it doesn't work

I asked this question other times but i was asked to clarify my question so i hope it will go.

 // 6 min =360,000 millisecond
final long millis=360000;

new CountDownTimer(millis,1000) {
    @Override
    public void onTick(long millisUntilFinished) {
        long halftime =millis/2;
        if (millisUntilFinished == halftime){
            Toast.makeText(CommentJouerActivity.this, "Halftime sir", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onFinish() {}
}.start();

Solution

  • Hmmm. I think I faced similar problem recently. You set tick rate to 1 second == 1000 milliseconds, but I think that onTick() method might have some minimal time shift (like 1 or 2 milliseconds per tick). Because of that you might miss the halftime by few milliseconds.

    I have few ideas for you.

    1) You can calculate halftime earlier, so it's not beeing calculated per every tick. And remove it from onTick() body.

    final long millis=360000;
    long halftime =millis/2;
    

    2) You can check halftime with some margin, for example half tick time:

    if (millisUntilFinished + 500 > halftime && millisUntilFinished - 500 < halftime) {
        Toast.makeText(CommentJouerActivity.this, "Halftime sir", Toast.LENGTH_SHORT).show();
    }