CountDownTimer
CountDownTimer 是android 自带的一个倒计时类,使用这个类可以很简单的实现 倒计时功能
CountDownTimer 的实现方式
1 new CountDownTimer(6000,1000) {//第一个参数表示的是倒计时的总时间,第二参数表示的是倒计时的间隔时间。 2 @Override 3 public void onTick(long millisUntilFinished) {//倒计时的过程 4 textView.setText(millisUntilFinished / 1000 + "秒"); 5 } 6 7 @Override 8 public void onFinish() {//倒计时结束 9 textView.setText("倒计时结束"); 10 } 11 }.start();
实现效果

取消计时器
调用 CountDownTimer 的 cancel() 方法,可以为我们取消计时器:但是这个方法,只有在 android 5.0 以上才有效果,在android 5.0 以下并没有效果。如果需要在android 5.0 以下的系统中也使用 cancel,需要我们自己根据 CountDownTimer 源码中的 实现方式,重新实现一下。 cancel()源码
1 /** 2 * Cancel the countdown. 3 */ 4 public synchronized final void cancel() { 5 mCancelled = true; 6 mHandler.removeMessages(MSG); 7 } 8 9 10 private static final int MSG = 1; 11 12 13 // handles counting down 14 private Handler mHandler = new Handler() { 15 16 @Override 17 public void handleMessage(Message msg) { 18 19 synchronized (CountDownTimer.this) { 20 if (mCancelled) { 21 return; 22 } 23 24 final long millisLeft = mStopTimeInFuture - SystemClock.elapsedRealtime(); 25 26 if (millisLeft <= 0) { 27 onFinish(); 28 } else if (millisLeft < mCountdownInterval) { 29 // no tick, just delay until done 30 sendMessageDelayed(obtainMessage(MSG), millisLeft); 31 } else { 32 long lastTickStart = SystemClock.elapsedRealtime(); 33 onTick(millisLeft); 34 35 // take into account user's onTick taking time to execute 36 long delay = lastTickStart + mCountdownInterval - SystemClock.elapsedRealtime(); 37 38 // special case: user's onTick took more than interval to 39 // complete, skip to next interval 40 while (delay < 0) delay += mCountdownInterval; 41 42 sendMessageDelayed(obtainMessage(MSG), delay); 43 } 44 } 45 } 46 };
由于在 android 5.0以上 增加了一个
private boolean mCancelled = false;
所以我们只需要在 5.0 以下的系统中,去掉
1 if (mCancelled) { 2 return; 3 }
去掉这个判断即可。