Search This Blog

Sunday, December 30, 2012

Make the thread to display timer for the Games using the method to Display Time in HH:MM:SS format

Firstly make one static variable for the counter for the timer which increase the every sec.

static int con = 0;

Now make one thread in which it sleeps every one sec and display it in runOnUiThread. This thread used to Display the counter in HH:MM:SS format using the simply one formatTime method.


new Thread(new Runnable() {
@Override
public void run() {
while (true) {
runOnUiThread(new Runnable() {
@Override
public void run() {
counter.setText(formatTime(Long.parseLong("" + con)));
con++;
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();


The formatTime method to display the counter in HH:MM:SS format is below.



private String formatTime(long millis) {
String output = "00:00:00";
long seconds = millis;
long minutes = seconds / 60;
long hours = minutes / 60;

seconds = seconds % 60;
minutes = minutes % 60;
hours = hours % 60;

String minutesD = String.valueOf(minutes);
String hoursD = String.valueOf(hours);

if (minutes < 10)
minutesD = "0" + minutes;
if (hours < 10)
hoursD = "0" + hours;

output = hoursD + " : " + minutesD;
return output;
}



This is how we can put the Timer in Game or any part of coding where the difference between the time is needed at that time also we can set the kind of methods.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.