androidandroid-timer

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?


Solution

  • 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();