Mohit Suthar Mohit Suthar - 2 months ago 18
Android Question

Android StopWatch : Milliseconds with two digit

I have successfully implement stopwatch, but i am not getting proper milliseconds with two digit like this mm:ss.SS 02:54.12, my code is

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
}


i have also try this
final int mill = (int) (updatedTime % 1000);
but this is always getting 10, 20, 30...etc but i want to get 10,11,12,13..so on, if you have any idea about it plz help me.

Answer

You are incrementing by 100ms. You need to increment by 10ms and post the runnable with a delay of 10ms. You can format the long using 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.
}

Be aware that this relies on the delay time of the Handler as a timer. Each repetition will introduce a tiny error. These errors may add up over time, which isn't desirable for a stopwatch.

I would store the time when the stopwatch is started, and calculate elapsed time from that each update:

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