Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 倒計時的三種實作與 CountDownTimer 源碼解析

編輯:關於 Android 程式設計

倒計時是個看似簡單、實際寫法很多的功能。最常見的組合是 Timer + TimerTask + Handler,也可以搭配 Runnable;但如果不想自己造輪子,Android 本身其實已經準備好一個現成答案。

方案一:Timer + TimerTask + Handler

基本結構是:TimerTask 在背景按週期觸發,把數字放進 Message 丟給 Handler,Handler 在主執行緒更新 UI,倒數歸零時取消 Timer。

public class MainActivity extends Activity {

    Timer timer;
    TextView tv;
    Button b;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        tv = (TextView) findViewById(R.id.textView1);
        b  = (Button) findViewById(R.id.button1);

        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what > 0) {
                    tv.setText("" + msg.what);
                } else {
                    // Handler 裡可以安全更新 UI
                    tv.setText("倒時");
                    timer.cancel();
                }
            }
        };

        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                timer = new Timer();
                timer.schedule(new TimerTask() {
                    int i = 10;

                    @Override
                    public void run() {
                        Message msg = new Message();
                        msg.what = i--;
                        handler.sendMessage(msg);
                    }
                }, 1000, 200);
            }
        });
    }
}

這裡有個很容易踩的細節:timer.schedule(task, 5000) 和 timer.schedule(task, 1000, 5000) 完全是兩回事。前者是「5 秒後執行一次」,後者才是「1 秒後開始、每 5 秒重複一次」。少寫一個參數,倒計時就變成只跳一格。

方案二:封裝成自己的計時類(Handler + Runnable)

把邏輯收攏到一個獨立類裡,用一個 boolean 控制暫停/繼續,UI 只需要讀 getCurrentTime():

public class MyCountDownTimer {

    private long millisInFuture;
    private long countDownInterval;
    private boolean status;

    public MyCountDownTimer(long pMillisInFuture, long pCountDownInterval) {
        this.millisInFuture = pMillisInFuture;
        this.countDownInterval = pCountDownInterval;
        status = false;
        Initialize();
    }

    public void Stop()  { status = false; }
    public void Start() { status = true;  }
    public long getCurrentTime() { return millisInFuture; }

    public void Initialize() {
        final Handler handler = new Handler();
        final Runnable counter = new Runnable() {
            public void run() {
                long sec = millisInFuture / 1000;
                if (status) {
                    if (millisInFuture <= 0) {
                        Log.v("status", "done");
                    } else {
                        Log.v("status", sec + " seconds remain");
                        millisInFuture -= countDownInterval;
                        handler.postDelayed(this, countDownInterval);
                    }
                } else {
                    Log.v("status", sec + " seconds remain and timer has stopped!");
                    handler.postDelayed(this, countDownInterval);
                }
            }
        };
        handler.postDelayed(counter, countDownInterval);
    }
}

Activity 側只要三件事:建立物件、按開始、按暫停,再開一個每 100ms 刷新文字的 Runnable 把 getCurrentTime() 貼到 TextView 上。這樣計時邏輯與 UI 徹底分開,複用起來乾淨多了。

方案三:直接用 CountDownTimer(推薦)

Android 內建的 android.os.CountDownTimer 就是為這個場景設計的,只要繼承它並實作兩個方法:

public class NewActivity extends Activity {

    private MyCount mc;
    private TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        tv = (TextView) findViewById(R.id.show);
        mc = new MyCount(30000, 1000);
        mc.start();
    }

    /* 倒計時內部類 */
    class MyCount extends CountDownTimer {
        public MyCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            tv.setText("done");
        }

        @Override
        public void onTick(long millisUntilFinished) {
            tv.setText("seconds remaining: " + millisUntilFinished / 1000);
        }
    }
}

onTick() 按 countDownInterval 週期呼叫,onFinish() 在時間到時呼叫一次,中途想中止就呼叫 cancel()。

源碼看它怎麼做到

public abstract class CountDownTimer {

    private final long mMillisInFuture;
    private final long mCountdownInterval;
    private long mStopTimeInFuture;

    public CountDownTimer(long millisInFuture, long countDownInterval) {
        mMillisInFuture = millisInFuture;
        mCountdownInterval = countDownInterval;
    }

    public final void cancel() {
        mHandler.removeMessages(MSG);
    }

    public synchronized final CountDownTimer start() {
        if (mMillisInFuture <= 0) {
            onFinish();
            return this;
        }
        mStopTimeInFuture = SystemClock.elapsedRealtime() + mMillisInFuture;
        mHandler.sendMessage(mHandler.obtainMessage(MSG));
        return this;
    }

    public abstract void onTick(long millisUntilFinished);
    public abstract void onFinish();

    private static final int MSG = 1;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            synchronized (CountDownTimer.this) {
                final long millisLeft = mStopTimeInFuture - SystemClock.elapsedRealtime();

                if (millisLeft <= 0) {
                    onFinish();
                } else if (millisLeft < mCountdownInterval) {
                    // 不再 tick,直接睡到結束
                    sendMessageDelayed(obtainMessage(MSG), millisLeft);
                } else {
                    long lastTickStart = SystemClock.elapsedRealtime();
                    onTick(millisLeft);

                    // 把 onTick 本身的執行時間也計算進去
                    long delay = lastTickStart + mCountdownInterval - SystemClock.elapsedRealtime();

                    // 特殊情況:onTick 執行時間超過一個 interval,直接跳到下一格
                    while (delay < 0)
                        delay += mCountdownInterval;

                    sendMessageDelayed(obtainMessage(MSG), delay);
                }
            }
        }
    };
}

幾個值得學的設計:

  • 用 SystemClock.elapsedRealtime() 而非 currentTimeMillis(),前者不受使用者改系統時間影響, also 是單調遞增的。
  • 每次 tick 都把 onTick() 的執行耗時計入下一次延遲,避免誤差隨時間累積;若 onTick 太慢,用 while 迴圈直接補到下一個整格,不會爆發式連發。
  • start() 與 handleMessage() 都用 synchronized 保護,因為 onTick 的呼叫之間不會重入。

最後提醒一個容易忽略的細節:以 30 秒、1 秒 interval 為例,畫面上最後顯示的是 1,也就是說 onTick 實際只被呼叫了 29 次。如果你需要精確的「執行 n 次」,設定時長要記得留一格餘量,寫成 n+1 才對得上。

結論很明確:需要週期性任務時,優先考慮 CountDownTimer;只有當需求超出它的能力(例如需要真正可取消、可暫停、跨頁面存活的計時器)時,才值得自己封裝,此時也建議改用 Handler 或協程,並記得在 onDestroy 中回收,避免記憶體洩漏。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved