這是個抽象類,我以爲這個定時器實現有點簡單,可是具備不穩定性,也就有點意思;也許你對它的實現會感興趣,請跟我來bash
private final long mMillisInFuture;
private final long mCountdownInterval;
private long mStopTimeInFuture;
private boolean mCancelled = false;
複製代碼
執行總時長,執行間隔,中止時間,可取消; 執行總時長,執行間隔,經過構造器傳入ide
核心成員變量oop
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
synchronized (CountDownTimer.this) {
if (mCancelled) {
return;
}
final long millisLeft = mStopTimeInFuture - SystemClock.elapsedRealtime();
if (millisLeft <= 0) {
onFinish();
} else {
long lastTickStart = SystemClock.elapsedRealtime();
onTick(millisLeft);
long lastTickDuration = SystemClock.elapsedRealtime() - lastTickStart;
long delay;
if (millisLeft < mCountdownInterval) {
delay = millisLeft - lastTickDuration;
if (delay < 0) delay = 0;
} else {
delay = mCountdownInterval - lastTickDuration;
while (delay < 0) delay += mCountdownInterval;
}
sendMessageDelayed(obtainMessage(MSG), delay);
}
}
}
};
複製代碼
public abstract void onTick(long millisUntilFinished);
public abstract void onFinish();
複製代碼
定時結束、每次任務執行ui
public synchronized final void cancel() {
mCancelled = true;
mHandler.removeMessages(MSG);
}
public synchronized final CountDownTimer start() {
mCancelled = false;
if (mMillisInFuture <= 0) {
onFinish();
return this;
}
mStopTimeInFuture = SystemClock.elapsedRealtime() + mMillisInFuture;
mHandler.sendMessage(mHandler.obtainMessage(MSG));
return this;
}
複製代碼
經過消息機制取消;經過消息機制進行定時執行this
這樣的定時器,被使用場景裹住了腳,用起來賊有意思spa
技術變化都很快,但基礎技術、理論知識永遠都是那些;做者但願在餘後的生活中,對經常使用技術點進行基礎知識分享;若是你以爲文章寫的不錯,請給與關注和點贊;若是文章存在錯誤,也請多多指教!線程