Timer with Chronometer

1

I am developing an application and it uses the timer by clicking on the play to start and pause for it to pause, but when I click again on play How could I continue counting the time?

java code:

public class FutebolSimples extends AppCompatActivity {

    private ImageButton imgButton_play, imgButton_pause, imgButton_1, imgButton_2;
    private TextView txt_valor1, txt_valor2;
    private int contador = 0;
    private int contador1 = 0;
    private Chronometer reloginho;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_futebol_simples);


        imgButton_1 = (ImageButton) findViewById(R.id.imgButton_1);
        imgButton_2 = (ImageButton) findViewById(R.id.imgButton_2);
        imgButton_play = (ImageButton) findViewById(R.id.imgButton_play);
        imgButton_pause = (ImageButton) findViewById(R.id.imgButton_pause);
        reloginho = (Chronometer) findViewById(R.id.chronometer);
        txt_valor1 = (TextView) findViewById(R.id.txt_valor1);
        txt_valor2 = (TextView) findViewById(R.id.txt_valor2);

        imgButton_play.setEnabled(true);
        imgButton_pause.setEnabled(false);
        imgButton_1.setEnabled(false);
        imgButton_2.setEnabled(false);


        imgButton_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imgButton_play.setEnabled(false);
                imgButton_pause.setEnabled(true);
                imgButton_1.setEnabled(true);
                imgButton_2.setEnabled(true);

                reloginho.setBase(SystemClock.elapsedRealtime());
                reloginho.start();
            }
        });

        imgButton_pause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imgButton_play.setEnabled(true);
                imgButton_pause.setEnabled(false);
                imgButton_1.setEnabled(false);
                imgButton_2.setEnabled(false);

                reloginho.stop();
            }
        });
    }
}

Thank you.

    
asked by anonymous 30.08.2016 / 21:54

1 answer

3

To not zero the value you have to add SystemClock.elapsedRealtime() to the time that was paused with .stop() using any variable initialized with 0 . Example:

long tempoPausado = 0;

Update the value of the variable when you stop the timer like this:

tempoPausado = reloginho.getBase() - SystemClock.elapsedRealtime();
mChronometer.stop();

So you can use this variable to set the timer before you start it:

reloginho.setBase(SystemClock.elapsedRealtime() + tempoPausado);

Good Luck! =)

    
30.08.2016 / 22:07