公共方法
public final void cancel ()
取消倒計時(取消后,再次啟動會重新開始倒計時)
public abstract void onFinish ()
倒計時完成時被調(diào)用
public abstract void onTick (long millisUntilFinished)
固定間隔被調(diào)用 參數(shù) millisUntilFinished 倒計時剩余時間只嚣。
public synchronized final CountDownTimer start ()
啟動倒計時
//十分鐘倒計時
private MyCountDownTimer timer;
private final long TIME = 600 * 1000L;
private final long INTERVAL = 1000L;
private long leftoverTime;
//十分鐘倒計時
class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onTick(long millisUntilFinished) {
leftoverTime = millisUntilFinished / 1000;
if (leftoverTime <= 59) {
binding.tvTimeCount.setText(String.format("00:%02d", leftoverTime));
} else {
binding.tvTimeCount.setText(String.format("%02d:%02d", leftoverTime / 60, leftoverTime % 60));
}
}
@Override
public void onFinish() {
cancelTimer();
}
}
/**
* 開始倒計時
*/
private void startTimer() {
if (timer == null) {
timer = new MyCountDownTimer(TIME, INTERVAL);
}
timer.start();
}
/**
* 取消倒計時
*/
private void cancelTimer() {
if (timer != null) {
timer.cancel();
timer = null;
}
}