Android API自帶的"計(jì)時(shí)"類,簡(jiǎn)單分析源碼
1柄延、CountDownTimer的啟動(dòng):
/**
* Start the countdown.
*/
public synchronized final CountDownTimer start() {
//開關(guān)拦焚,每次start必須確保開關(guān)是打開狀態(tài)
mCancelled = false;
//總時(shí)間不能小于0
if (mMillisInFuture <= 0) {
//結(jié)束的回調(diào)函數(shù)
onFinish();
return this;
}
//結(jié)束時(shí)間為當(dāng)前時(shí)間+總時(shí)間
mStopTimeInFuture = SystemClock.elapsedRealtime() + mMillisInFuture;
//發(fā)送消息
mHandler.sendMessage(mHandler.obtainMessage(MSG));
return this;
}
2秕衙、Handler 接收消息
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
//線程鎖,多線程操作可能會(huì)導(dǎo)致millisLeft 的差異
synchronized (CountDownTimer.this) {
//開關(guān)為關(guān)閉狀態(tài)
if (mCancelled) {
return;
}
final long millisLeft = mStopTimeInFuture - SystemClock.elapsedRealtime();
if (millisLeft <= 0) {
onFinish();
//mCountdownInterval為計(jì)時(shí)的時(shí)間間隔
} else if (millisLeft < mCountdownInterval) {
// no tick, just delay until done 剩余時(shí)間小于間隔時(shí)間,直接發(fā)送延遲剩余時(shí)間
sendMessageDelayed(obtainMessage(MSG), millisLeft);
}
剩余時(shí)間大于間隔時(shí)間曼追,直接發(fā)送延遲間隔時(shí)間
else {
long lastTickStart = SystemClock.elapsedRealtime();
//每次計(jì)時(shí)回調(diào)該函數(shù)礼殊,同時(shí)傳遞剩余時(shí)間
onTick(millisLeft);
// take into account user's onTick taking time to execute
long delay = lastTickStart + mCountdownInterval - SystemClock.elapsedRealtime();
// special case: user's onTick took more than interval to
// complete, skip to next interval 最后回調(diào)一次onTick
while (delay < 0) delay += mCountdownInterval;
sendMessageDelayed(obtainMessage(MSG), delay);
}
}
}
};
3晶伦、取消計(jì)時(shí):
public synchronized final void cancel() {
mCancelled = true;
mHandler.removeMessages(MSG);
}
為何取消的時(shí)候handleMessage不執(zhí)行onFinish()呢?
理當(dāng)加上啊..
4泌参、關(guān)于SystemClock
常用的API;
SystemClock.currentThreadTimeMillis();//1970 00:00:00到現(xiàn)在過(guò)去的毫秒數(shù)
SystemClock.elapsedRealtime();//手機(jī)從啟動(dòng)到現(xiàn)在的運(yùn)行時(shí)間盖溺,且包括系統(tǒng)sleep(CPU關(guān)閉)的時(shí)間
SystemClock.uptimeMillis();//手機(jī)從啟動(dòng)到現(xiàn)在的運(yùn)行時(shí)間,且不包括系統(tǒng)sleep(CPU關(guān)閉)的時(shí)間
5拙友、小結(jié)
完全使用的Handler機(jī)制歼郭,未另外開辟新的線程或者Timer病曾,延遲間隔時(shí)間后sendMessages泰涂,handler收到消息后繼續(xù)sendMessages逼蒙,簡(jiǎn)單的遞歸是牢,很巧妙驳棱,用法自定義View里面很常見社搅。