2016-09-13 68 views
0

我已經成功實現秒錶,但我沒有得到適當的毫秒數,如下所示的兩位數mm:ss。 SS 02:54。 ,我的代碼是Android秒錶:兩位數毫秒

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..so上,如果你有任何想法,請幫我。

回答

1

您正在增加100ms。您需要增加10毫秒,並將延遲10毫秒後運行。您可以使用SimpleDateFormat格式化長整型。

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); 
    } 
}; 
+0

感謝您的回覆,但我沒有得到適當的毫秒爲使用此我變得像這樣30:00.70,30:00.80,但我想像30:00.71,30:00.72這個 –

+0

你的增量是100ms。使用10ms代替 –

+0

我的秒錶將很慢 –

0

使用stopWatchHandler.postDelayed(此,10);

+1

那麼我的秒錶將會非常慢 –

0
stopWatchHandler.postDelayed(this, 100); 
timeMill=timeMill+100; 

100ms = 0,1s 
10ms = 0,01s 

您正在更新計時器的每十秒鐘。

+0

我不明白你在說什麼? –

1
  timeMill=timeMill+100; 
      updateTime(timeMill/100); 
      stopWatchHandler.postDelayed(this, 10); 
+0

你是否通過我的代碼得到任何問題,因爲它在我的最後工作。 –

0

這是因爲你更新的代碼stopWatchHandler.postDelayed(this, 100);所以它計算像stopwatch每隔10秒鐘:0.1, 0.2, 0.3, ...

您應將其更改爲: stopWatchHandler.postDelayed(this, 10);