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

Android 使用 CountDownTimer 實作倒計時效果

編輯:關於 Android 程式設計

倒計時是個高頻需求,短信驗證碼的重發倒數就是最典型的例子。我之前的做法是 Handler 加 Timer 加 TimerTask 三件套,直到發現 Android 早就封裝好了 CountDownTimer,果斷換掉。相信不少人跟我一樣,一開始并不知道有這個現成的類別。

CountDownTimer 顧名思義就是倒數計時器,內部以 Handler 機制實作,把背景執行緒的建立與 Handler 佇列的維護都封裝好了。整類只對外暴露四個方法:

(1)public abstract void onTick(long millisUntilFinished):固定間隔被呼叫,需自行覆寫。

(2)public abstract void onFinish():倒計時歸零時被呼叫,需自行覆寫。

(3)public synchronized final void cancel():取消倒計時,再次呼叫 start 會重新計時。

(4)public synchronized final CountDownTimer start():啟動倒計時。

程式碼範例

package com.per.countdowntimer;

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

public class MainActivity extends Activity {

    private TextView mTvShow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTvShow = (TextView) findViewById(R.id.show);
    }

    /** 取消倒計時 */
    public void oncancel(View v) {
        timer.cancel();
    }

    /** 開始倒計時 */
    public void restart(View v) {
        timer.start();
    }

    private CountDownTimer timer = new CountDownTimer(10000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            mTvShow.setText((millisUntilFinished / 1000) + "秒後可重發");
        }

        @Override
        public void onFinish() {
            mTvShow.setEnabled(true);
            mTvShow.setText("獲取驗證碼");
        }
    };
}

對應的 XML 佈局:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:orientation="vertical"
    android:padding="16dp">

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

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:onClick="restart"
        android:text="取消" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:onClick="oncancel"
        android:text="結束" />
</LinearLayout>

參數說明

CountDownTimer timer = new CountDownTimer(10000, 1000) 的兩個參數都以毫秒為單位:

第一個參數是總時長,也就是從呼叫 start() 到 onFinish() 被觸發之間的毫秒數,這裡是 10 秒。

第二個參數是 onTick 的呼叫間隔,這裡是每 1000 毫秒一次,因此 onTick 總共會被呼叫約 10 次。

使用時直接 timer.start() 即可。

實務上有兩個地方要多留意。一是 onTick 回傳的 millisUntilFinished 是「剩餘毫秒」,並非固定值,用它除以 1000 做整數除法時,第一次可能是 9 而不是 10,若要顯示 10 開始,需要自行向上取整。二是 timer 物件被建立時並不會自動啟動,且若在 Activity 內以匿名類別建立,記得在 onDestroy 中呼叫 cancel(),否則倒計時結束前的回呼會持有已銷毀的 Activity 參考,造成記憶體洩漏。

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