【问题标题】:Android StopWatch : Milliseconds with two digitAndroid秒表:两位数的毫秒
【发布时间】:2017-01-20 23:54:57
【问题描述】:

我已经成功实现秒表,但我没有得到像 mm:ss 这样的两位数的正确毫秒数。SS 02:54.12,我的代码是

private Runnable updateTimerThread = new Runnable() {
    public void run() {
        timeMill=timeMill+100;
        updateTime(timeMill);
        stopWatchHandler.postDelayed(this, 100);
    }
};



    private void updateTime(long updatedTime) {
       //I want to convert this updateTime to Milliseonds like two digit 23
}

我也试过这个final int mill = (int) (updatedTime % 1000); 但这总是得到 10、20、30...等等,但我想得到 10、11、12、13..等等,如果你有任何想法请帮帮我。

【问题讨论】:

    标签: android runnable stopwatch


    【解决方案1】:

    您正在递增 100 毫秒。您需要增加 10 毫秒并以 10 毫秒的延迟发布可运行文件。您可以使用 SimpleDateFormat 格式化 long。

    private Runnable updateTimerThread = new Runnable() {
        public void run() {
            timeMill += 10;
            updateTime(timeMill);
            stopWatchHandler.postDelayed(this, 10);
        }
    };
    
    private void updateTime(long updatedTime) {
        DateFormat format = new SimpleDateFormat("mm:ss.SS");
        String displayTime = format.format(updatedTime);
        // Do whatever with displayTime.
    }
    

    请注意,这依赖于 Handler 作为计时器的延迟时间。每次重复都会引入一个微小的错误。这些错误可能会随着时间的推移而累积,这对于秒表来说是不可取的。

    我会存储秒表启动的时间,并计算每次更新所经过的时间:

    startTime = System.nanoTime();
    //Note nanoTime isn't affected by clock or timezone changes etc
    
    private Runnable updateTimerThread = Runnable() {
        public void run() {
            long elapsedMiliseconds = (System.nanoTime() - startTime()) / 1000;
            updateTime(elapsedMiliseconds);
            stopWatchHandler.postDelayed(this, 10);
        }
    };
    

    【讨论】:

    • 感谢您的回复,但我没有得到适当的毫秒来使用这个我得到这样的 30:00.70、30:00.80,但我想要 30:00.71、30:00.72 这个
    • 您的增量为 100 毫秒。改为使用 10 毫秒
    • 我的秒表会很慢
    【解决方案2】:

    使用 stopWatchHandler.postDelayed(this, 10);

    【讨论】:

    • 那我的秒表会很慢
    【解决方案3】:
    stopWatchHandler.postDelayed(this, 100);
    timeMill=timeMill+100;
    
    100ms = 0,1s  
    10ms = 0,01s
    

    你的计时器每十分之一秒更新一次。

    【讨论】:

    • 我听不懂你在说什么?
    【解决方案4】:
                timeMill=timeMill+100;
                updateTime(timeMill/100);
                stopWatchHandler.postDelayed(this, 10);
    

    【讨论】:

    • 你对我的代码有任何问题吗,因为它在我的最终工作。
    【解决方案5】:

    这是因为您在此代码stopWatchHandler.postDelayed(this, 100); 中每十秒更新一次stopwatch,所以它的计数为:0.1, 0.2, 0.3, ...

    您应该将其更改为: stopWatchHandler.postDelayed(this, 10);

    【讨论】:

      猜你喜欢
      • 2013-07-28
      • 2012-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-17
      • 2014-09-19
      相关资源
      最近更新 更多