Reputation: 85
I'm making a stopwatch application for android. I have one button for start and stop. My problem is that the time is increasing very fast. Where i'm getting wrong. Bellow is the code:
final Runnable updater = new Runnable() {
public void run() {
if (startIsPressed) {
time = SystemClock.elapsedRealtime() - initStart + startPointTime;
startPointTime = time;
} else {
time = startPointTime;
}
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));
handler.postDelayed(this, 30);
}
};
startBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (!startIsPressed) {
startIsPressed = true;
startBtn.setText(R.string.stop);
initStart = SystemClock.elapsedRealtime();
handler.post(updater);
} else {
startIsPressed = false;
startBtn.setText(R.string.start);
handler.post(updater);
}
}
});
}
Upvotes: 0
Views: 1695
Reputation: 132982
as doc say postDelayed Causes the Runnable r to be added to the message queue, to be run after the specified amount of time elapses.Update your timer every 1 second as: use
handler.postDelayed(this, 100); //100 milliseconds refresh rate
instead of
handler.postDelayed(this, 30); //30 milliseconds refresh rate
and see stopwatch logic here
Upvotes: 1