概述
在平時我們編程的時候,經常會用到倒計時這個功能,很多人不知道Android已經幫封裝好了一個類,往往都自己寫。現在發現了這個類,大家共享一下
CountDownTimer 使用
CountDownTimer countDownTimer=new CountDownTimer(10*1000+1000, 1000) { @Override public void onTick(long millisUntilFinished) { int time= (int) (millisUntilFinished/1000); tv.setText(String.valueOf(time)); } @Override public void onFinish() { tv.setText("倒計時完畢"); } }; countDownTimer.start();//調用該方法即可開始倒計時。
說明一下:CountDownTimer countDownTimer=new CountDownTimer(10*1000+1000, 1000)中,第一個參數表示總時間,第二個參數表示間隔時間。意思就是每隔一秒會回調一次方法onTick,然後10秒之後會回調onFinish方法。
CountDownTimer源碼解析
首先我們先從它的構造方法開始查看源碼,它構造方法如下所示:
public CountDownTimer(long millisInFuture, long countDownInterval) { mMillisInFuture = millisInFuture; mCountdownInterval = countDownInterval; }
第一個參數表示倒計時的總時間,第二個參數表示倒計時的間隔時間,
緊接着我們查看CountDownTimers的start()方法如下所示:
/** * Start the countdown. */ public synchronized final CountDownTimer start() { mCancelled = false; if (mMillisInFuture <= 0) {//如果傳入的總時間小於等於0則直接結束。 onFinish(); return this; } mStopTimeInFuture = SystemClock.elapsedRealtime() + mMillisInFuture;//獲取當前時間並加上傳入的總時間, mHandler.sendMessage(mHandler.obtainMessage(MSG)); return this; }
如上我們可以知道CountDownTimers的start()方法會通過mHandler將消息發送出去,我們先看看接收消息地方的源碼,如下所示:
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); // take into account user's onTick taking time to execute long lastTickDuration = SystemClock.elapsedRealtime() - lastTickStart; long delay; if (millisLeft < mCountdownInterval) { // just delay until done delay = millisLeft - lastTickDuration; // special case: user's onTick took more than interval to // complete, trigger onFinish without delay if (delay < 0) delay = 0; } else { delay = mCountdownInterval - lastTickDuration; // special case: user's onTick took more than interval to // complete, skip to next interval while (delay < 0) delay += mCountdownInterval; } sendMessageDelayed(obtainMessage(MSG), delay); } } } };
從上面源碼我們可以知道,當未到倒計時結束時間時會調用onTick()方法,否則會調用onFinish()方法,而這兩個方法都是抽象方法,因此需要子類實現該方法,兩個方法源碼如下所示:
/** * 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();
看完源碼終於知道了它的工作原理,原來也不是很難。