萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android 控件上實現倒計時功能的最佳實踐

在用戶註冊、登錄驗證、支付倒計時等場景中,需要在按鈕或 TextView 上顯示倒計時並控制交互狀態。Android 提供的 CountDownTimer 類是實現此功能的標準方案,本文通過完整示例演示如何優雅地實現可復用的倒計時邏輯。

倒計時效果演示圖

核心實現:繼承 CountDownTimer 抽象類

完整 Activity 代碼

public class CountdownTimerActivity extends AppCompatActivity {

    private TimeCount timeCounter;
    private Button btnVerify;

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

        // 總時長 60 秒,間隔 1 秒回調
        timeCounter = new TimeCount(60 * 1000, 1000);
        btnVerify = findViewById(R.id.btn_verify);

        btnVerify.setOnClickListener(v -> {
            if (!timeCounter.isRunning()) {
                timeCounter.start();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 關鍵:銷毀時取消計時器,防止內存洩漏與崩潰
        if (timeCounter != null) {
            timeCounter.cancel();
        }
    }

    /**
     * 倒計時內部類
     * @param millisInFuture 總時長(毫秒)
     * @param countDownInterval 回調間隔(毫秒)
     */
    private class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            // 計時過程:禁用按鈕,顯示剩餘秒數
            btnVerify.setEnabled(false);
            btnVerify.setText(String.format(Locale.getDefault(), "%d秒後重試", millisUntilFinished / 1000));
        }

        @Override
        public void onFinish() {
            // 計時結束:恢復按鈕狀態
            btnVerify.setEnabled(true);
            btnVerify.setText("重新獲取驗證碼");
        }
    }
}

關鍵最佳實踐總結

1. 生命週期管理

必須在 onDestroy() 中調用 cancel(),否則 Activity 銷毀後計時器仍在後台運行,導致:

  • 內存洩漏(持有 Activity 引用)
  • 崩潰(嘗試更新已銷毀 View)
  • 用戶體驗異常(重新進入頁面倒計時狀態錯亂)

2. 狀態持久化(進階需求)

若需應對「用戶退出應用後重新進入仍保持倒計時」,需:

  • 在 onPause() 保存 System.currentTimeMillis() + millisUntilFinished 至 SharedPreferences
  • 在 onResume() 讀取時間差,若未過期則恢復倒計時

3. UI 線程安全

onTick() 和 onFinish() 已在主線程回調,可直接操作 View,無需 runOnUiThread()。

4. 參數靈活配置

將總時長、間隔提取為常量或配置項,支持不同業務場景(如 60 秒驗證碼、30 秒支付倒計時、10 秒廣告跳過)。

5. 視覺反饋增強

  • 文字顏色漸變(紅→灰→綠)
  • 添加圓形進度條背景
  • 結束時播放輕微震動/音效

現代化替代方案

Kotlin 協程寫法更簡潔:

// 在 ViewModel 或 Lifecycle-aware 組件中
viewModelScope.launch {
    var seconds = 60
    btnVerify.isEnabled = false
    while (seconds > 0) {
        btnVerify.text = "${seconds}s"
        delay(1000)
        seconds--
    }
    btnVerify.isEnabled = true
    btnVerify.text = "重新獲取"
}

掌握 CountDownTimer 的正確使用姿勢,能讓您的應用在驗證碼、秒殺、廣告跳過等高頻場景中提供流暢、穩定的用戶體驗。

copyright © 萬盛學電腦網 all rights reserved