Android之倒计时CountDownTimer

作者: 奔跑的图腾 | 来源:发表于2018-03-11 13:08 被阅读250次

    公共方法

    public final void cancel ()
             取消倒计时(取消后,再次启动会重新开始倒计时)  
    
    public abstract void onFinish ()
             倒计时完成时被调用     
    
    public abstract void onTick (long millisUntilFinished)
             固定间隔被调用     参数 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;
    }
    }
    

    相关文章

      网友评论

      本文标题:Android之倒计时CountDownTimer

      本文链接:https://www.haomeiwen.com/subject/iouvfftx.html