I am building a game in Android 2.2 but I'm struggling to be able to show a timer on screen during play and saving the time to a Leaderboard upon Game Over.
I have a game loop and I've extended the SurfaceView to show my graphics.
I don't think my game loop
runs accurately every millisecond so I'm finding it difficult to grab the time.
I want to get to having a stored variable called time
storing the milliseconds and a method called getFormattedTime()
which would get the time as Minutes:Seconds:Milliseconds
Whats the best way to do this?
You can get the current time in milliseconds since January 1, 1970 by calling System.currentTimeMillis()
. You can then take a difference between a stored value and a new currenTimeMillis to determine the amount of milliseconds that have passed.
Try the above if not getting as you wished you can try this but its rounding around
Calendar c = Calendar.getInstance();
int seconds = c.get(Calendar.SECOND);
int min= c.get(Calendar.MINUTE);
String time=min+":"+seconds
I've resolved this myself by creating a Timer
and TimerTask
and using these as a separate loop for timekeeping purposes. Thanks to all for your help anyway.
There is a class named TimerTask in Java. It allows to perform the activity on certain period of interval. You can use this class to create a timer for your game application.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.