80,471
社区成员




/**
* 自定义倒计时<br/>
* Created by cds on 2016/8/29.
*/
public abstract class CountDownTimerUtil {
private boolean mCancelled = false;
private long mStopTimeInFuture;
private final long countTime;
private final long intervalTime;
private CountDownHandler mHandler;
private static final int MSG = 1;
public CountDownTimerUtil(long countTime, long intervalTime) {
this.countTime = countTime;
this.intervalTime = intervalTime;
mHandler = new CountDownHandler(this);
}
private static class CountDownHandler extends Handler{
private WeakReference<CountDownTimerUtil> weakReference;
public CountDownHandler(CountDownTimerUtil util){
weakReference = new WeakReference<>(util);
}
@Override
public void handleMessage(Message msg) {
if (weakReference != null && weakReference.get() != null) {
CountDownTimerUtil timerUtil = weakReference.get();
if (timerUtil.mCancelled) {
return;
}
final long millisLeft = timerUtil.mStopTimeInFuture - SystemClock.elapsedRealtime();
//LogUtil.d("millisLeft:" + millisLeft);
if (millisLeft <= 0) {
timerUtil.onFinish();
} else {
// 校准时间
long wait = (millisLeft % timerUtil.intervalTime == 0 ? timerUtil.intervalTime : millisLeft % timerUtil.intervalTime);
sendMessageDelayed(obtainMessage(MSG), wait);
timerUtil.onTick(millisLeft);
}
}
}
}
public synchronized final void cancel() {
mCancelled = true;
mHandler.removeMessages(MSG);
onFinish();
}
/**
* 开始
*/
public synchronized final CountDownTimerUtil start() {
mCancelled = false;
if (countTime <= 0) {
onFinish();
return this;
}
mStopTimeInFuture = SystemClock.elapsedRealtime() + countTime;
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();
}