Android通用倒计时器

例如,倒计时从5到3

new CountDownTimerUtils(5999, 1000, 3000, new CountDownTimerUtils.CallBackListener() {
                    @Override
                    public void onTick(long millisUntilFinished) {
                        text = String.valueOf(millisUntilFinished / 1000);
                        invalidate();
                        Log.e(TAG, "onTick: " + millisUntilFinished);
                    }

                    @Override
                    public void onFinish() {
                        Log.e(TAG, "onFinish: ");
                    }
                });
package com.example.zhangyu.myrecorder.Utils;

import android.os.CountDownTimer;


public class CountDownTimerUtils extends CountDownTimer {

    private CallBackListener listener;

    private long endMs;

    private boolean isFinished;

    public interface CallBackListener {
        void onTick(long millisUntilFinished);

        void onFinish();
    }

    /**
     * @param startMs    开始时间
     * @param intervalMs 每隔多少毫秒回调一次
     * @param endMs      结束时间
     * @param listener
     */
    public CountDownTimerUtils(long startMs, long intervalMs, long endMs, CallBackListener listener) {
        super(startMs, intervalMs);
        this.endMs = endMs;
        this.listener = listener;
        start();
    }

    @Override
    public void onTick(long millisUntilFinished) {
        if (millisUntilFinished <= endMs) {
            if (listener != null) {
                listener.onFinish();
                listener = null;
                isFinished = true;
            }
        } else {
            if (listener != null) {
                listener.onTick(millisUntilFinished);
            }
        }
    }

    @Override
    public void onFinish() {
       if (!isFinished){
           listener.onFinish();
       }
    }

}


你可能感兴趣的:(Android基础)