Search code examples
androidtimercountdowncountdowntimer

How to add and remove time on CountDownTimer?


The question is: How can I add or remove time from the CountDownTimer during the count down?

For example: The user does something good: +5sec, the user does something wrong: -5sec.

Can someone help me with some code?


Solution

  • Maybe something like this

    abstract class MyTimer {
    
        public MyTimer(long deadline, long interval)
        {
            mDeadline = deadline;
            mInterval = interval; 
    
            mTimer = new MyCountDownTimer(mDeadline, mInterval);
    
        }
    
        public synchronized void start() {
    
           mTimer.start();
    
        }
    
        public abstract void onTick(long time);
        public abstract void onFinish();
    
        public synchronized void userDidRight() 
        {
            mTimer.cancel();
            mTimer = new MyCountDownTimer(mDeadline, mInterval += 5000);
            mTimer.start();
        }
    
        public synchronized void userDidWrong() 
        {
            mTimer.cancel();
            mTimer = new MyCountDownTimer(mDeadline, mInterfval -= 5000);
            mTimer.start();
        }
    
    
        private class MyCountDownTimer extends CountDownTimer() {
    
            private abstract void onFinish() {
                MyTimer.this.onFinish();
            }
    
            private abstract void onTick(long time) {
                MyTimer.this.onTick(time);
            }
        }
    
        private MyCountDownTimer mTimer;
    }