在android中使用倒计时器显示天数小时分秒的倒计时问题

hem*_*mar 3 android

我在我的应用程序中使用倒数计时器,我需要显示即将到来的日期,以小时,分钟和秒为单位.我得到了日,小时,分钟和秒,但是当我将其设置为文本视图时倒计时没有开始.是我的代码.

Date date = new Date(2013,Integer.parseInt(datess.get(k).split("-")[1])-1,Integer.parseInt(datess.get(k).split("-")[0]),hours,mins,secs);  
     long dtMili = System.currentTimeMillis();  
     Date dateNow = new Date(dtMili);  
      remain = date.getTime() - dateNow.getTime();


MyCount counter = new MyCount(remain,1000);
            counter.start();

public class MyCount extends CountDownTimer{
    public MyCount(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
        }



    @Override
    public void onFinish() {
        // TODO Auto-generated method stub

        tv3.setText("done");
    }

    @Override
    public void onTick(long millisUntilFinished) {
        // TODO Auto-generated method stub


        tv3.setText(timeCalculate(millisUntilFinished/1000) + " Countdown");

    }
}

 public String timeCalculate(long ttime)   
   {  
     long  daysuuu,hoursuuu, minutesuuu, secondsuuu;  
     String daysT = "", restT = "";  



     daysuuu = (Math.round(ttime) / 86400);  
     hoursuuu = (Math.round(ttime) / 3600) - (daysuuu * 24);  
     minutesuuu = (Math.round(ttime) / 60) - (daysuuu * 1440) - (hoursuuu * 60);  
     secondsuuu = Math.round(ttime) % 60;  


     if(daysuuu==1) daysT = String.format("%d day ", daysuuu);  
     if(daysuuu>1) daysT = String.format("%d days ", daysuuu);  

     restT = String.format("%02d:%02d:%02d", hoursuuu, minutesuuu, secondsuuu);  

     return daysT + restT;  
   }  
Run Code Online (Sandbox Code Playgroud)

这是输出

在此输入图像描述

为什么倒计时没有开始?任何建议表示赞赏.

Sam*_*Sam 6

您没有使用该millisUntilFinished参数来更新您的时间timeCalculate().从...开始:

@Override
public void onTick(long millisUntilFinished) {
    tv3.setText(millisUntilFinished + " Countdown");
}
Run Code Online (Sandbox Code Playgroud)

一旦确认计时器正在运行,您将需要一种方法来转换millisUntilFinished为人类可读的字符串.

与Java中的日期和时间相关的类不必要地使用并且具有一些模糊的错误.(例如,大多数Date类都已弃用,但推荐的Calendar类仍然严重依赖于Date ...)第三方库Joda Time是一个受欢迎的替代品.


加成

输出不是我的预期

未来25,000至700天不是我所期望的,date似乎是错误的.正如加布里埃尔在这个问题的另一个答案中指出的那样,年份值是从1900年开始计算的.虽然其他东西仍然是错误的,因为未来25,000天不到70年......
但是这个构造函数已被弃用,不应该使用,日历是推荐的课程.我为你写了一个使用Calendar 的快速演示.

但要了解CountDownTimer本身有一些基本缺陷:

  • 每次onTick()被称为CDT 都会在整个时间内增加几毫秒,我注意到它每天可以轻松添加7分半钟.
  • 由于第一个错误,最后一个onTick()可能没有被调用.当从5倒计时,我通常会看到"5, 4, 3, 2, <long pause>"那么onFinished()显示"0"...

我在之前的一个问题中重写了CDT:android CountDownTimer - 刻度之间的额外毫秒延迟.