I'm trying to create a timer app, but I have this problem with milliseconds.
When someone activates the timer I save the current milliseconds and then I just this to get the difference between them
long startMillisecond;
long i = System.currentMillisecond() - startMillisecond
and then I display this variable i
with some other code. However when I pause my program my variable i
stays on the right value, but when I start the program again I get the "wrong" value since System.currentMillisecond()
keeps increasing (internally), so it looks like it "jumps" over a couple of seconds
Example: Start app > variable i = System.currentMillisecond() - startMillisecond
is equal to 0. And now if I pause for 5 seconds and then resume my variable i
have the value of 5.
Anyone knows how I can let it be on the same value when I paus?
EDIT. Here is my code for my run function
String tempstring;
int millisec,sec,min,hour;
Handler handler;
Runnable runnable;
SensorManager mSensor;
Sensor accSensor;
Button startButton,stopButton,resetButton;
TextView whiteplayertime,blackplayertime,xt,yt,zt;
public void StartTimer(View view){
mSensor.registerListener(this, accSensor, SensorManager.SENSOR_DELAY_NORMAL);
handler = new Handler();
runnable = new Runnable() {
@Override
public void run() {
if(startmillisec <= 0){
startmillisec = System.currentTimeMillis();
}
tempmillisec = System.currentTimeMillis() - startmillisec;
millisec = tempmillisec;
millisec /= 100;
millisec = millisec % 10;
sec = TU.MILLISECONDS.toSeconds(tempmillisec);
sec = sec % 60;
min = TU.MILLISECONDS.toMinutes(tempmillisec);
min = min % 60;
hour = TU.MILLISECONDS.toHours(tempmillisec);
hour = hour % 24;
tempstring = String.format("%02d:%02d:%02d:%d",hour,min,sec,millisec);
whiteplayertime.setText(tempstring);
handler.post(this); //This is the last in the code
}
};
handler.post(runnable);
Simple save elapsed from the last stop value and save in a variable if the timer is ongoing or not.
public MyTimer {
private long startTime;
private long elapsed;
private boolean running;
public void start() {
startTime = System.currentTimemillis();
running = true;
}
public void stop() {
elapsed = elapsed + System.currentTimemillis() - startTime;
running = false;
}
public long getElapsed() {
if (running) {
return elapsed + System.currentTimemillis() - startTime;
} else {
return elapsed;
}
}
}