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

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("重新獲取驗證碼");
}
}
}
必須在 onDestroy() 中調用 cancel(),否則 Activity 銷毀後計時器仍在後台運行,導致:
若需應對「用戶退出應用後重新進入仍保持倒計時」,需:
onPause() 保存 System.currentTimeMillis() + millisUntilFinished 至 SharedPreferencesonResume() 讀取時間差,若未過期則恢復倒計時onTick() 和 onFinish() 已在主線程回調,可直接操作 View,無需 runOnUiThread()。
將總時長、間隔提取為常量或配置項,支持不同業務場景(如 60 秒驗證碼、30 秒支付倒計時、10 秒廣告跳過)。
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 的正確使用姿勢,能讓您的應用在驗證碼、秒殺、廣告跳過等高頻場景中提供流暢、穩定的用戶體驗。