Android中实现倒计时的几种方式

zqm112112 8年前
   <h3><strong>1、使用CountDownTimer</strong></h3>    <pre>  <code class="language-java">private void fun1(){      final CountDownTimer countDownTimer = new CountDownTimer(60000,1000) {          @Override          public void onTick(long l) {              //倒计时每秒的回调              mainBinding.tvUp.setText(l/1000+"");          }          @Override          public void onFinish() {              //倒计时结束          }      };      countDownTimer.start();  }</code></pre>    <h3><strong>2、使用 Handler + Thread</strong></h3>    <pre>  <code class="language-java">private boolean isOk = true;  private int time = 59;  private Handler handler = new Handler(){      public void handleMessage(android.os.Message msg) {          if(msg.what == 0){              mainBinding.tvDown.setText("" + time);              time--;              if(time<=0){                  isOk = false;              }          }      };  };      private void fun2(){      new Thread(){          @Override          public void run() {              while(isOk){                  try {                      Thread.sleep(1000);                      handler.sendEmptyMessage(0);                  } catch (InterruptedException e) {                      e.printStackTrace();                  }              }          }      }.start();  }</code></pre>    <h3><strong>3、使用属性动画(经过对比,发现属性动画倒计时不准确)</strong></h3>    <pre>  <code class="language-java">private void fun2(){          ValueAnimator valueAnimator = ValueAnimator.ofInt(60000,0);          valueAnimator.setDuration(60000);          valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {              @Override              public void onAnimationUpdate(ValueAnimator valueAnimator) {                  int value = (int)(valueAnimator.getAnimatedValue());                  mainBinding.tvMiddle.setText(value/1000+"");              }          });          valueAnimator.start();      }</code></pre>    <p> </p>    <p>来自:http://www.jianshu.com/p/137f24f0c43c</p>    <p> </p>