android 倒计时工具类

时间:2022-06-20 22:00:12

Android 原声的CountDownTimer类存在计时不准有时候会跳转、不能到0秒的情况,而且时间是毫秒级,感觉用的不太习惯 ,所以根据CountDownTimer的源码自己修改为秒级的,而且可以倒计时到0秒,特记录下,只要在构造方法里传入倒计时秒数即可.

/**  * @Date 2018/3/16 11:08  * @TODO 倒计时工具类(秒)  */ public abstract class CountTimeUtils {
        /**  * Millis since epoch when alarm should stop.  */  private final long mMillisInFuture;

        private long mStopTimeInFuture;

        /**  * boolean representing if the timer was cancelled  */  private boolean mCancelled = false;

        /**  * @param secondInFuture The number of millis in the future from the call  * to {@link #start()} until the countdown is done and {@link #onFinish()}  * is called.  */  public CountTimeUtils(long secondInFuture) {
            mMillisInFuture = secondInFuture;
        }

        /**  * Cancel the countdown.  */  public synchronized final void cancel() {
            mCancelled = true;
            mHandler.removeMessages(MSG);
        }

        /**  * Start the countdown.  */  public synchronized final CountTimeUtils start() {
            mCancelled = false;
            if (mMillisInFuture <= 0) {
                onFinish();
                return this;
            }
            mStopTimeInFuture = (SystemClock.elapsedRealtime()/1000) + mMillisInFuture;
            mHandler.sendMessage(mHandler.obtainMessage(MSG));
            return this;
        }


        /**  * Callback fired on regular interval.  * @param millisUntilFinished The amount of time until finished.  */  public abstract void onTick(long millisUntilFinished);

        /**  * Callback fired when the time is up.  */  public abstract void onFinish();

        private static final int MSG = 1;

        // handles counting down  private Handler mHandler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                synchronized (CountTimeUtils.this) {
                    if (mCancelled) {
                        return;
                    }
                    final long millisLeft = mStopTimeInFuture - (SystemClock.elapsedRealtime()/1000);
                    if (millisLeft < 0) {
                        onFinish();
                    } else {
                        onTick(millisLeft);
                        sendMessageDelayed(obtainMessage(MSG), 1000);
                    }
                }
            }
        };
    }