I have a 10 and 20 question game. I need to count how much time is passed when a user finishes the game.
Timer T=new Timer(); T.scheduleAtFixedRate(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { public void run() { countdown.setText(""+count); count++; } }); } }, 1000, 1000);
I use this to stop the counter:
T.cancel();
Now I need two things:
Per the Android docs SystemClock. elapsedRealtime() is the recommend basis for general purpose interval timing. As others have said, the elapsedRealtime() answer below is correct.
When the game starts:
long tStart = System.currentTimeMillis();
When the game ends:
long tEnd = System.currentTimeMillis(); long tDelta = tEnd - tStart; double elapsedSeconds = tDelta / 1000.0;
Per the Android docs SystemClock.elapsedRealtime()
is the recommend basis for general purpose interval timing. This is because, per the documentation, elapsedRealtime() is guaranteed to be monotonic, [...], so is the recommend basis for general purpose interval timing.
The SystemClock documentation has a nice overview of the various time methods and the applicable use cases for them.
SystemClock.elapsedRealtime()
and SystemClock.elapsedRealtimeNanos()
are the best bet for calculating general purpose elapsed time.SystemClock.uptimeMillis()
and System.nanoTime()
are another possibility, but unlike the recommended methods, they don't include time in deep sleep. If this is your desired behavior then they are fine to use. Otherwise stick with elapsedRealtime()
.System.currentTimeMillis()
as this will return "wall" clock time. Which is unsuitable for calculating elapsed time as the wall clock time may jump forward or backwards. Many things like NTP clients can cause wall clock time to jump and skew. This will cause elapsed time calculations based on currentTimeMillis()
to not always be accurate.When the game starts:
long startTime = SystemClock.elapsedRealtime();
When the game ends:
long endTime = SystemClock.elapsedRealtime(); long elapsedMilliSeconds = endTime - startTime; double elapsedSeconds = elapsedMilliSeconds / 1000.0;
Also, Timer() is a best effort timer and will not always be accurate. So there will be an accumulation of timing errors over the duration of the game. To more accurately display interim time, use periodic checks to System.currentTimeMillis()
as the basis of the time sent to setText(...)
.
Also, instead of using Timer
, you might want to look into using TimerTask
, this class is designed for what you want to do. The only problem is that it counts down instead of up, but that can be solved with simple subtraction.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With