Android: CountDownTimer skips last onTick()!

前端 未结 12 671
眼角桃花
眼角桃花 2020-11-27 14:51

Code:

public class SMH extends Activity {  

    public void onCreate(Bundle b) {  
        super.onCreate(b);  
        setContentView(R.layou         


        
12条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-27 15:15

    I also faced the same issue with CountDownTimer and I tried different approaches. So one of the easiest ways is in solution provided by @Nantoca - he suggests to double the frequency from 1000ms to 500ms. But I don't like this solution because it makes more work which will consume some extra battery resource.

    So I decided to use @ocanal's soultion and to write my own simple CustomCountDownTimer.

    But I found couple of flaws in his code:

    1. It's a bit inefficient (creating second handler to publish results)

    2. It starts to publish first result with a delay. (You need to do a post() method rather than postDelayed() during first initialization)

    3. odd looking. Methods with capital letter, status instead of classic isCanceled boolean and some other.

    So I cleaned it a bit and here is the more common version of his approach:

    private class CustomCountDownTimer {
    
        private Handler mHandler;
        private long millisUntilFinished;
        private long countDownInterval;
        private boolean isCanceled = false;
    
        public CustomCountDownTimer(long millisUntilFinished, long countDownInterval) {
            this.millisUntilFinished = millisUntilFinished;
            this.countDownInterval = countDownInterval;
            mHandler = new Handler();
        }
    
        public synchronized void cancel() {
            isCanceled = true;
            mHandler.removeCallbacksAndMessages(null);
        }
    
        public long getRemainingTime() {
            return millisUntilFinished;
        }
    
        public void start() {
    
            final Runnable counter = new Runnable() {
    
                public void run() {
    
                    if (isCanceled) {
                        publishUpdate(0);
                    } else {
    
                        //time is out
                        if(millisUntilFinished <= 0){
                            publishUpdate(0);
                            return;
                        }
    
                        //update UI:
                        publishUpdate(millisUntilFinished);
    
                        millisUntilFinished -= countDownInterval;
                        mHandler.postDelayed(this, countDownInterval);
                    }
                }
            };
    
            mHandler.post(counter);
        }
    }
    

提交回复
热议问题