Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android game countdown timer

I'm working on a game where I need a countdown timer.

I need to be able to pause the timer, resume the countdown and to add some time to current countdown state.

I've looked at CountdownTimer class and its methods, but it seems like it doesn't have the required features.

I need advice - which component is best for this case?

How to use it?

What are the possible problems?

Thread? AsyncTask? Timer?

Does anyone have experience with this?

like image 928
Veljko Avatar asked Dec 14 '25 16:12

Veljko


1 Answers

I think Thread can be used, but its easier to implement your features using CountdownTimer wrapper class:

    static class MyCountdownTimer {

    long mCurrentMilisLeft;
    long mInterval;
    CountdownTimerWrapper mCountdownTimer;

    class CountdownTimerWrapper extends CountDownTimer{
        public CountdownTimerWrapper(long millisInFuture,long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {

        }

        @Override
        public void onTick(long millisUntilFinished) {
            mCurrentMilisLeft = millisUntilFinished;
        }

    }

    public MyCountdownTimer(long millisInFuture, long countDownInterval) {          
        set(millisInFuture,countDownInterval);
    }

    public void pause(){
        mCountdownTimer.cancel();
    }

    public void resume(){
        mCountdownTimer = new CountdownTimerWrapper(mCurrentMilisLeft, mInterval);
        mCountdownTimer.start();
    }

    public void start(){
        mCountdownTimer.start();
    }

    public void set(long millisInFuture, long countDownInterval){
        mInterval = countDownInterval;
        mCurrentMilisLeft = millisInFuture;         
        mCountdownTimer = new CountdownTimerWrapper(millisInFuture, countDownInterval);
    }

}
like image 70
skoperst Avatar answered Dec 17 '25 05:12

skoperst



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!