软件编程
位置:首页>> 软件编程>> Android编程>> Android中CountDownTimer 实现倒计时功能

Android中CountDownTimer 实现倒计时功能

作者:木木木木头脑袋  发布时间:2022-01-03 00:00:24 

标签:CountDownTimer,倒计时

CountDownTimer

CountDownTimer 是android 自带的一个倒计时类,使用这个类可以很简单的实现 倒计时功能

CountDownTimer 的实现方式 


new CountDownTimer(6000,1000) {//第一个参数表示的是倒计时的总时间,第二参数表示的是倒计时的间隔时间。
         @Override
         public void onTick(long millisUntilFinished) {//倒计时的过程
           textView.setText(millisUntilFinished / 1000 + "秒");
         }

@Override
         public void onFinish() {//倒计时结束
           textView.setText("倒计时结束");
         }
       }.start();

实现效果

Android中CountDownTimer 实现倒计时功能

取消计时器

调用 CountDownTimer 的 cancel() 方法,可以为我们取消计时器:但是这个方法,只有在 android 5.0 以上才有效果,在android 5.0 以下并没有效果。如果需要在android 5.0 以下的系统中也使用 cancel,需要我们自己根据 CountDownTimer 源码中的 实现方式,重新实现一下。


 /**
  * Cancel the countdown.
  */
 public synchronized final void cancel() {
   mCancelled = true;
   mHandler.removeMessages(MSG);
 }

private static final int MSG = 1;

// handles counting down
 private Handler mHandler = new Handler() {

@Override
   public void handleMessage(Message msg) {

synchronized (CountDownTimer.this) {
       if (mCancelled) {
         return;
       }

final long millisLeft = mStopTimeInFuture - SystemClock.elapsedRealtime();

if (millisLeft <= 0) {
         onFinish();
       } else if (millisLeft < mCountdownInterval) {
         // no tick, just delay until done
         sendMessageDelayed(obtainMessage(MSG), millisLeft);
       } else {
         long lastTickStart = SystemClock.elapsedRealtime();
         onTick(millisLeft);

// take into account user's onTick taking time to execute
         long delay = lastTickStart + mCountdownInterval - SystemClock.elapsedRealtime();

// special case: user's onTick took more than interval to
         // complete, skip to next interval
         while (delay < 0) delay += mCountdownInterval;

sendMessageDelayed(obtainMessage(MSG), delay);
       }
     }
   }
 };

由于在 android 5.0以上 增加了一个


private boolean mCancelled = false;

所以我们只需要在 5.0 以下的系统中,去掉


if (mCancelled) {
         return;
       }

去掉这个判断即可。

来源:https://segmentfault.com/a/1190000009296018

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com