chronometer doesn't stop in android
In my app I want to show a stop timer watch. When I searched through Google I found an option called Chronometer in the developers site. It look's just like a stop timer watch.
When I click the start button I want the timer to get started and when I click the pause button the timer must be paused when once I click the start it must start from the time it's been stopped.
But in this chronometer开发者_如何学Go it get's started from 0 and when I click pause at 1min 10 sec it get paused. When I click once again start after 5min, the timer start the count from 6min 10sec, even at pause the timer is running, how to stop this and get resumed at the time it is been stopped.
Following is my code for chronometer
Start = (Button)findViewById(R.id.widget306);
Start.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
chronometer.start();
}
});
Stop = (Button)findViewById(R.id.widget307);
Stop.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
chronometer.stop();
}
});
}
Sorry, but I've found a solution myself and it seems much simpler:
In your activity, declare a member variable(e.g. lastPause) to record the time of your last pause:
private long lastPause;
Start your timer (assume the variable of your timer is crono):
crono.setBase(SystemClock.elapsedRealtime());
crono.start();
Pause your timer each time using:
lastPause = SystemClock.elapsedRealtime();
crono.stop();
Resume your timer each time using:
crono.setBase(crono.getBase() + SystemClock.elapsedRealtime() - lastPause);
crono.start();
I've not tested the precision precisely yet as it seems to be ok by my eyes :]
From the Chronometer doc
Stop counting up. This does not affect the base as set from setBase(long), just the view display.
I dont have any android dev environment right now, so cant investigate on it more :(
Edit:
is it the code you have based your code on ? It seems to use setBase
to the current time on stop
I faced the same issue and I fixed it by using the following code:
chronometerInstance.setBase(SystemClock.elapsedRealtime());
chronometerInstance.stop();
This is stopped my chronometer counting to 00:00.
The following works wonders:
final long lastPause = SystemClock.elapsedRealtime();
mChronometer.stop();
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mActivity)
.setCancelable(false)
.setMessage("Stop chronometer while AlertDialog is asking something.")
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
mChronometer.setBase(mChronometer.getBase()
+ SystemClock.elapsedRealtime()
- lastPause);
mChronometer.start();
}
});
alertDialogBuilder.create().show();
This snippet is just about stopping the chronometer and showing an AlertDialog. When the Dialog is closed the chronometer will start from it's last position.
精彩评论