Android倒计时工具类

public abstract class TimeDownUtil {
    private final String TAG = getClass().getSimpleName();

    private long mCountDownInterval = 1000;
    private Timer mTimer;
    private TimerTask mTimerTask;

    /**
     * 时钟回调的次数
     */
    private int mCount = 0;

    /**
     * 倒计时时间,默认间隔单位为秒
     *
     * @param time 毫秒
     */
    public TimeDownUtil(final long time) {
        initTimer(time);
    }

    private void initTimer(long time) {
        mTimer = new Timer();
        mCount = (int) (time / mCountDownInterval);
        LogUtil.w(TAG, "count = " + mCount);
        mTimerTask = new TimerTask() {
            @Override
            public void run() {
                LogUtil.w(TAG, "mCount = " + mCount);
                if (mCount > 0) {
                    mCount--;
                    onTick(mCountDownInterval * mCount);
                } else {
                    onFinish();
                    cancel();
                }
            }
        };
    }

    /**
     * 倒计时时间,默认单位为秒
     *
     * @param time
     * @param countDownInterval 间隔时间,1000为1s
     */
    public TimeDownUtil(long time, long countDownInterval) {
        mCountDownInterval = countDownInterval;
        initTimer(time);
    }

    public void start() {
        mTimer.schedule(mTimerTask, 0, mCountDownInterval);
    }

    /**
     * Callback fired on regular interval.
     *
     * @param millisUntilFinished 距离结束还有多少时间
     */
    public abstract void onTick(long millisUntilFinished);

    /**
     * 倒计时结束的回调
     */
    public abstract void onFinish();

    public void cancel() {
        mTimer.cancel();
        mTimerTask.cancel();
    }


}

关注公众号回复“小程序”获取1000个小程序打包源码。回复“大数据”获取多本大数据电子书

发表评论

电子邮件地址不会被公开。 必填项已用*标注