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

用 CountDownTimer 類輕鬆實作 Android 倒數計時

編輯:關於 Android 程式設計

以前寫倒數,多半是自己開一條線程 sleep 再回主線程更新 UI,麻煩又容易出錯。翻資料時發現系統其實早就提供了 android.os.CountDownTimer,於是果斷拋棄舊做法。這個類只要給兩個參數就能運作,還免費附帶取消與重新開始的能力。

兩個參數就上手

new MyCountDownTimer(30000, 1000);
  • 第一個參數 millisInFuture:以毫秒為單位的總時長,30000 就是 30 秒。
  • 第二個參數 countDownInterval:呼叫 onTick() 的間隔,1000 代表每秒回呼一次。
  • mc.start() 開始;mc.cancel() 取消。

實作:繼承並重寫兩個回呼

只需要覆寫 onTick()(每次間隔觸發)與 onFinish()(時間到)。

package com.example.daojishi;

import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    private MyCountDownTimer mc;
    private TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView) findViewById(R.id.show);
        mc = new MyCountDownTimer(30000, 1000);
        mc.start();
    }

    public void oncancel(View view) {
        Toast.makeText(MainActivity.this, "取消", Toast.LENGTH_LONG).show();
        mc.cancel();
    }

    public void restart(View view) {
        Toast.makeText(MainActivity.this, "重新開始", Toast.LENGTH_LONG).show();
        mc.start();
    }

    /** 繼承 CountDownTimer,重寫 onTick() 與 onFinish() */
    class MyCountDownTimer extends CountDownTimer {

        /**
         * @param millisInFuture 倒數總毫秒數,1000 即 1 秒
         * @param countDownInterval 每隔多少毫秒呼叫一次 onTick()
         */
        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

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

        @Override
        public void onTick(long millisUntilFinished) {
            Log.i("MainActivity", millisUntilFinished + "");
            tv.setText("倒計時(" + millisUntilFinished / 1000 + ")...");
        }
    }
}

對應的版面配置

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/show"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/button1"
        android:onClick="oncancel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/show"
        android:layout_below="@+id/show"
        android:layout_marginLeft="50dp"
        android:layout_marginTop="106dp"
        android:text="cancel" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_marginTop="63dp"
        android:onClick="restart"
        android:text="restart" />

</RelativeLayout>

附錄:CountDownTimer 源碼

讀一遍源碼會發現它的實作比想像中簡潔——本質上就是一個 Handler 加上「下次該觸發的時間點」。

package android.os;

import android.util.Log;

/**
 * Schedule a countdown until a time in the future, with
 * regular notifications on intervals along the way.
 */
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) {
                    // 不足一個間隔,直接等到結束即可
                    sendMessageDelayed(obtainMessage(MSG), millisLeft);
                } else {
                    long lastTickStart = SystemClock.elapsedRealtime();
                    onTick(millisLeft);
                    // 把 onTick() 本身的執行時間也計算進去
                    long delay = lastTickStart + mCountdownInterval
                            - SystemClock.elapsedRealtime();
                    // 若 onTick() 執行太久,直接跳到下一個間隔
                    while (delay < 0) {
                        delay += mCountdownInterval;
                    }
                    sendMessageDelayed(obtainMessage(MSG), delay);
                }
            }
        }
    };
}

源碼中有兩個細節值得記住:一是 onTick() 的呼叫彼此同步,前一次沒跑完,後一次不會插隊;二是它會把 onTick() 的執行耗時從下次延遲中扣除,所以即使回呼裡做事稍慢,總時長也不會被拖長。反過來說,如果 onTick() 裡放了太重的運算,UI 一樣會卡,這點和用不用 CountDownTimer 無關。

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