首页 > 其他分享 >Android将倒计时做到极致

Android将倒计时做到极致

时间:2022-10-03 12:38:07浏览次数:189  
标签:mTimes void private 倒计时 mCountDownInterval 极致 mCallBack Android public


public class CountDownTimer {

private int mTimes;
private int allTimes;
private final long mCountDownInterval;
private final Handler mHandler;
private OnTimerCallBack mCallBack;
private boolean isStart;
private long startTime;

public CountDownTimer(int times, long countDownInterval){
this.mTimes = times;
this.mCountDownInterval = countDownInterval;
mHandler = new Handler();
}

public synchronized void start(OnTimerCallBack callBack){
this.mCallBack = callBack;
if (isStart || mCountDownInterval <= 0){
return;
}

isStart = true;
if (callBack != null){
callBack.onStart();
}
startTime = SystemClock.elapsedRealtime();

if (mTimes <= 0){
finishCountDown();
return;
}
allTimes = mTimes;

mHandler.postDelayed(runnable, mCountDownInterval);
}

private final Runnable runnable = new Runnable() {
@Override
public void run() {
mTimes--;
if (mTimes > 0){
if (mCallBack != null){
mCallBack.onTick(mTimes);
}

long nowTime = SystemClock.elapsedRealtime();
long delay = (nowTime - startTime) - (allTimes - mTimes) * mCountDownInterval;
// 处理跳秒
while (delay > mCountDownInterval){
mTimes --;
if (mCallBack != null){
mCallBack.onTick(mTimes);
}

delay -= mCountDownInterval;
if (mTimes <= 0){
finishCountDown();
return;
}
}

mHandler.postDelayed(this, 1000 - delay);
}else {
finishCountDown();
}
}
};

private void finishCountDown(){
if (mCallBack != null){
mCallBack.onFinish();
}
isStart = false;
}

public void cancel(){
mHandler.removeCallbacksAndMessages(null);
isStart = false;
}

public interface OnTimerCallBack{

void onStart();

void onTick(int times);

void onFinish();

}

}

​Android将倒计时做到极致 =

标签:mTimes,void,private,倒计时,mCountDownInterval,极致,mCallBack,Android,public
From: https://blog.51cto.com/u_11288266/5730079

相关文章