Android game countdown timer

2019-04-10 17:59发布

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?

1条回答
祖国的老花朵
2楼-- · 2019-04-10 18:11

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);
    }

}
查看更多
登录 后发表回答