Chronometer does not stop in android

In my application I want to show a stopwatch. When I searched on Google, I found the Chronometer option on the developers site. It looks just like a stopwatch watch.

When I press the start button, I want the timer to start working, and when I press the pause button, the timer should be paused, when I press the start button, it should start from the moment it stops.

But in this chronometer, it starts at 0, and when I press a pause of 1 minute 10 seconds, it pauses. When I press again, I start after 5 minutes, the timer will start the counter from 6 minutes 10 seconds, even when the timer is paused, it works, how to stop it and resume when it stops.

Below is my chronometer code

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();
            }
        });
    }
+5
3

doc

. setBase (long), .

- Android- , : (

: ? , setBase

+1

, , :

  • - (, lastPause) :

    private long lastPause;

  • (, - crono):

    crono.setBase(SystemClock.elapsedRealtime());

    crono.start();

  • , :

    lastPause = SystemClock.elapsedRealtime();

    crono.stop();

  • , :

    crono.setBase(crono.getBase() + SystemClock.elapsedRealtime() - lastPause);

    crono.start();

, , , :]

+22

The following 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 simply stops the chronometer and displays an AlertDialog. When the Dialog is closed, the chronometer will start from the last position.

0
source

All Articles