Maja
Maja

Reputation: 59

How to parse values from chronometer (android)?

I am currently trying to create an android application for which I need the time elapsed in seconds since clicking the start button until clicking the stop button. Currently I have a timer which uses the following code in the java class:

//on start timer
public void startTimer(View view){
    myChronometer.setBase(SystemClock.elapsedRealtime());
    myChronometer.start();
}

//on stop timmer
public void stopTimer(View view){
    myChronometer.stop();
}

followed by the below code in the xml file for the same class:

    <Chronometer
    [...]
    android:id="@+id/chronometer" />

<Button
    android:text="Stop"
    [...]
    android:onClick="stopTimer"/>

<Button
    android:text="Start"
    [...]
    android:onClick="startTimer" />

Is there any way I could pass the time elapsed (in sec) using the chronometer to another method in the same java class?

Upvotes: 1

Views: 1102

Answers (1)

lelloman
lelloman

Reputation: 14183

apparently there is not method that returns the value (check here) but you can compute it yourself easily:

SystemClock.elapsedRealtime() - myChronometer.getBase()

if you need to access the time after you've stopped the chronometer you can do something like this

private long timerTime = Long.MIN_VALUE;

//on start timer
public void startTimer(View view){
    myChronometer.setBase(SystemClock.elapsedRealtime());
    myChronometer.start();
    timerTime = Long.MIN_VALUE;
}       

//on stop timmer
public void stopTimer(View view){
    myChronometer.stop();
    timerTime = SystemClock.elapsedRealtime() - myChronometer.getBase();
}

private long getTimerTime(){
    if(timerTime == Long.MIN_VALUE){
        return SystemClock.elapsedRealtime() - myChronometer.getBase();
    }

    return timerTime;
}

Upvotes: 1

Related Questions