平时开发中经常遇到需要倒计时执行某个操作的需求,整理了一个倒计时工具类,需要时可以用上,在此记录
import android.os.CountDownTimer;
/**
* @class describe
* @anthor alias.su
* @time 2022/11/15 14:10
* @change * @chang time * @class describe
*/
public class CountDownUtil {
private static final String TAG = "CountDownUtil";
private static CountDownUtil checkUtil;
private static Object obj = new Object();
private CountListener listener;
private CountDownTimer timer;
private boolean running = false;
private long countTime = 0;
//检测超时时间
private final int TIME_OUT_TIME = 10;
public static synchronized CountDownUtil getInstance() {
synchronized (obj) {
if (checkUtil == null) {
checkUtil = new CountDownUtil();
}
}
return checkUtil;
}
public void startCount() {
countTime = 0;
if (timer == null) {
timer = new CountDownTimer(Integer.MAX_VALUE, 1000) {
@Override
public void onTick(long l) {
//还剩多少时间,十秒走一次
if (countTime > TIME_OUT_TIME) {
if (listener != null) {
stopCount();
}
}
countTime++;
}
@Override
public void onFinish() {
if (listener != null) {
listener.finish();
}
}
};
}
if (!running) {
timer.start();
running = true;
}
}
/**
* 重置计时时间
*/
public void resetTime() {
countTime = 0;
}
public void stopCount() {
if (timer != null) {
timer.cancel();
countTime = 0;
if (listener != null) {
listener.timeOut();
}
running = false;
}
}
public void setListener(CountListener listener) {
this.listener = listener;
}
public interface CountListener {
void timeOut();
void finish();
}
}