OoO 3
OoO 3

Reputation: 113

How to use Interval in countDownTimer in Android

In my application i should use CountDownTimer and for this I want use this library : CountdownView.
I want when lasted 5s show me Toast.
For example : I want show 17s countTimer, when this timer receive to 5s show me toast "just 5s".
I use this code, but show me ever 5s .

long time1 = 17 * 1000;
mCvCountdownViewTest1.start(time1);
mCvCountdownViewTest1.setOnCountdownIntervalListener(5000, new CountdownView.OnCountdownIntervalListener() {
    @Override
    public void onInterval(CountdownView cv, long remainTime) {
        Toast.makeText(MainActivity.this, "Just 5s ", Toast.LENGTH_SHORT).show();
    }
});

I want just lasted 5s not ever 5s.

how can i it?

Upvotes: 1

Views: 2401

Answers (2)

Denysole
Denysole

Reputation: 4051

I think you should check how many seconds remains. I rewrote your code:

long time1 = 17L * 1000;
mCvCountdownViewTest1.start(time1);
mCvCountdownViewTest1.setOnCountdownIntervalListener(1000, new CountdownView.OnCountdownIntervalListener() {
    @Override
    public void onInterval(CountdownView cv, long remainTime) {
        long remainTimeInSeconds = remainTime / 1000;
        if (remainTimeInSeconds  == 5) {
            Toast.makeText(MainActivity.this, "Just 5s ", Toast.LENGTH_SHORT).show();
        }
    }
});

Upvotes: 0

Avijit Karmakar
Avijit Karmakar

Reputation: 9388

By modifying your code:

boolean toastShown = false;
long time1 = 17 * 1000;
mCvCountdownViewTest1.start(time1);
mCvCountdownViewTest1.setOnCountdownIntervalListener(1000, new CountdownView.OnCountdownIntervalListener() {
    @Override
    public void onInterval(CountdownView cv, long remainTime) {
        if(remainTime < 5000 && !toastShown) {
            toastShown = true;
            Toast.makeText(MainActivity.this, "Just 5s ", Toast.LENGTH_SHORT).show();
        }
    }
});

You can try this code also:

CountDownTimer countDownTimer = new CountDownTimer(17000, 1000) {
    @Override
    public void onTick(long millisUntilFinished) {
        Toast.makeText(HomeActivity.this, "running" + millisUntilFinished, Toast.LENGTH_SHORT).show();
        if (millisUntilFinished < 5000) {
            Toast.makeText(HomeActivity.this, "5 sec left", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onFinish() {
        Toast.makeText(HomeActivity.this, "Countdown Timer Finished", Toast.LENGTH_SHORT).show();
    }
};
countDownTimer.start();

Upvotes: 2

Related Questions