I'm making stopwatch application for Android. I want when stop is clicked the time to stop, and when the Start is clicked again the time to be resumed. I'm using http://www.goldb.org/stopwatchjava.html class. Currently the time is resumed on click on Start button, but when i click Stop after second time it's showing bad time. Again on Start button the time is resumed correctly. Here's my code:
Handler mHandler = new Handler()
{
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case MSG_START_TIMER:
timer.start(); //start timer
mHandler.sendEmptyMessage(MSG_UPDATE_TIMER);
break;
case MSG_UPDATE_TIMER:
time = timer.getElapsedTime() + timeStoped;
hh = time / 3600000;
hours.setText("" + formatter.format(hh));
time = time - hh * 3600000;
mm = time / 60000;
minutes.setText("" + formatter.format(mm));
time = time - mm * 60000;
ss = time / 1000;
seconds.setText("" + formatter.format(ss));
time = time - ss * 1000;
millis.setText("" + formatter.format(time / 10));
mHandler.sendEmptyMessageDelayed(MSG_UPDATE_TIMER,REFRESH_RATE); //text view is updated every second,
break;
//though the timer is still running
case MSG_STOP_TIMER:
mHandler.removeMessages(MSG_UPDATE_TIMER); // no more updates.
timer.stop();//stop timer
time = timer.getElapsedTime();
timeStoped = timeStoped + time;
hh = time / 3600000;
hours.setText("" + formatter.format(hh));
time = time - hh * 3600000;
mm = time / 60000;
minutes.setText("" + formatter.format(mm));
time = time - mm * 60000;
ss = time / 1000;
seconds.setText("" + formatter.format(ss));
time = time - ss * 1000;
millis.setText("" + formatter.format(time / 10));
break;
default:
break;
}
}
};
the Listener for the button Start/Stop :
startBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (!startIsPressed) {
mHandler.sendEmptyMessage(MSG_START_TIMER);
startIsPressed = true;
startBtn.setText(R.string.stop);
} else {
startIsPressed = false;
startBtn.setText(R.string.start);
mHandler.sendEmptyMessage(MSG_STOP_TIMER);
}
}
});
The solution is to replace:
time = timer.getElapsedTime();
timeStoped = timeStoped + time;
with:
time = timer.getElapsedTime() + timeStopped;
timeStopped = time;