6

I'm in the process of designing a chronometer / countdown timer app for Android 2.2 and would like one button press to start both the chronometer and the timer simultaneously. So, ideally, I'd like the seconds (time) on both the chronometer and timer to change at the same instance. (The timer will be counting down even as the chronometer is counting up). Since I'm using the chronometer and timer functionality provided by Android, I wrote the following piece of code when the user presses the 'Start' button

private boolean mStartPressedOnce = false;
long mTimeWhenStopped = 0;
Chronometer mChronometer;   
MyCounter mCounter;
...
@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.StartButton:
        // Perform some initialization for the chronometer depending
        // on the button press
        if (mStartPressedOnce == false) {
            mChronometer.setBase(SystemClock.elapsedRealtime());
        } else {
            mChronometer.setBase(SystemClock.elapsedRealtime() + mTimeWhenStopped);
        }

        // Perform the initialization for the timer
        mCounter = new MyCount(45000, 1000);

        // Fire up the chronometer  
        mChronometer.start();

        // Fire up the timer
        mCounter.start();
        break;

        case R.id.ResetButton:
            // Reset the chronometer  
            mChronometer.setBase(SystemClock.elapsedRealtime());
            mTimeWhenStopped = 0;
            break;

        case case R.id.StopButton:
            mStartPressedOnce = true;
            // Stop the chronometer 
            mTimeWhenStopped = mChronometer.getBase() - SystemClock.elapsedRealtime();
            mChronometer.stop();
            break;
    }

... 

public class MyCounter extends CountDownTimer {

    @Override
    public MyCount(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
    }

    @Override
    public void onFinish() {        
        // Nothing to do here
    }

    @Override
    public void onTick(long millisUntilFinished) {
        long seconds = (long) (millisUntilFinished / 1000);
        long minutes = (long) ((millisUntilFinished / 1000) / 60);
        long hours = (long) (((millisUntilFinished / 1000) / 60) / 60);

        // Do some formatting to make seconds, minutes and hours look pretty    

        // Update the timer TextView            
       (TextView) findViewById(R.id.CountDownTimerTextView))
           .setText(hours + ":" + minutes + ":" + seconds);
    }
}

Though it looks like the seconds on the chronometer and timer are in sync initially, after a short time, they seem to go off and the second updates for both occur at different times.

Was wondering what I could do to fix this. I did come across - and read this thread

Running multiple AsyncTasks at the same time -- not possible?

I realize that there may be a design change needed but I'm not sure exactly what needs to be done.

Edit: Included types for chronometer and timer and method for calculating time using Chronometer - per jolivier and njzk2's suggestions

3
  • 2
    what are your mChronometer and mCounter and how do you measure the time ?
    – njzk2
    Commented Nov 20, 2012 at 12:53
  • Why are you using widgets instead of System.nanoTime() or currentTimeMillis() ?
    – Shark
    Commented Nov 20, 2012 at 12:56
  • @Shark, not sure I know the answer to your question. Thanks.
    – aLearner
    Commented Nov 20, 2012 at 14:08

2 Answers 2

2

You can retrieve the current time with System.currentTimeMillis(), store it into a variable and forward it to both mChronometer and mCounter, so that they use the same time reference although their task started at different time.

Edit: with the given types, the android documentation about Chronometer will tell you that you can use elapsedRealTime to achieve what I said. CountDownTimer does not have this and its start method is final so you may want to use another implementation, a better view of your use case might help us.

Basically, wanting two threads to perform an action at the same millisecond is never a good idea, one of them will serve as the clock and the other one must be a slave and listen to the clock.

6
  • Thank you for your answer. I'm not sure I follow what you mean when you say that the value stored in the variable needs to be forwarded to mChronometer and mCounter. I did look at the mChronometer.start() and mCounter.start() methods but it looks like they don't accept an initial value (which would have been got by using System.currentTimeMillis() and stored there). So, in other words, there is nothing like mChronometer.start(initialVal) or mCounter.start(initialVal). Or did I just misunderstand your suggestion?
    – aLearner
    Commented Nov 20, 2012 at 12:58
  • could you give the type of mChronometer and mCounter in your question then? i'll need it to help you
    – jolivier
    Commented Nov 20, 2012 at 13:01
  • @njzk2 Just added some more code to make things clear. Thank you.
    – aLearner
    Commented Nov 20, 2012 at 13:12
  • @njzk2 added clarity to show how time is being calclated. Also, I'm indeed using elapsedRealTime per the documentation you pointed to. Thanks.
    – aLearner
    Commented Nov 20, 2012 at 14:07
  • I thought about this some more but still have not a clear way ahead. What can I change so that one is the master and one is the slave? Would this require a custom implementation of either a chronometer or timer, then? Assuming the chronometer implementation is retained and is considered the master, how can the timer be the slave?
    – aLearner
    Commented Nov 21, 2012 at 4:36
2

So, after mulling over this for some time and going off of the suggestion jolivier so generously shared with us, I realized that there exists a method called onChronometerTick which is called every time there is chronometer tick (every second, in this case). So, I thought of subtracting 1000 milliseconds from the counter every time the method is called and update the timer display accordingly. I got rid of the Android timer piece (CountDownTimer) completely. I figured this would be a nice way to have both displays update at the same time. It's also a simple implementation of a timer.

I'm happy to report that it seems to work well. Both the timer and chronometer displays indeed update at the same time. So, the original question looks like it's answered. Unfortunately, I ran into an off-by-two error on the timer front that I fixed with an ugly hack. I'm posting what I have so far. Any suggestions on how to fix the hack or improve the code are welcome. Note that I have commented the code to try to make it easy to understand what's been done.

Edit for bug: One more thing I noticed is that after around 10 minutes or so the chronometer and timer are off by one second. More precisely, the timer is behind the chronometer by one second. Not yet sure why this happens.

private boolean mStartPressedOnce = false;
long mTimeWhenStopped = 0;
Chronometer mChronometer;   
long millisUntilFinished = 0;
boolean firstPassOver = false;
int counter = 0;
...
@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.StartButton:
        // Perform some initialization for the chronometer depending
        // on the button press
        if (mStartPressedOnce == false) {
            mChronometer.setBase(SystemClock.elapsedRealtime());
        } else {
            mChronometer.setBase(SystemClock.elapsedRealtime() + mTimeWhenStopped);
        }

        // Fire up the chronometer  
        mChronometer.start();
        break;

        case R.id.ResetButton:
            // Reset the chronometer  
            mChronometer.setBase(SystemClock.elapsedRealtime());
            mTimeWhenStopped = 0;
            break;

        case case R.id.StopButton:
            mStartPressedOnce = true;
            // Stop the chronometer 
            mTimeWhenStopped = mChronometer.getBase() - SystemClock.elapsedRealtime();
            mChronometer.stop();
            break;
    }

... 

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.stop_watch);

    mChronometer = (Chronometer) findViewById(R.id.StopWatchTextView);

    // Initialize the number of milliseconds before the timer expires (
    // set the timer) - in this case to 46 seconds
    millisUntilFinished = 46000;

    // Display how many seconds remain before the timer expires
    ((TextView) findViewById(R.id.CountDownTimerTextView)).setText(hours
            + ":" + minutes + ":" + millisUntilFinished / 1000);

    // In line with the suggestion provided by  jolivier - make the timer
    // the slave and  update its display every time the chronometer 
    // ticks        
    mChronometer
            .setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {

                @Override
                public void onChronometerTick(Chronometer chronometer) {

                    // Update the display for the chronometer
                    CharSequence text = chronometer.getText();                  
                    chronometer.setText(text);

                    // Update the display for the timer                 
                    // !!! BUG !!!
                    // Looks like onChronometerTick is called at the 0th second
                    // and this causes an off by two error if a count down timer
                    // is being implemented. Fixed it with this hack. There's gotta
                    // be a more elegant solution, though.
                    if(counter >= 2) {
                        millisUntilFinished1 = millisUntilFinished1 - 1000;
                        counter = 2;
                    }
                    counter++;

                    if (millisUntilFinished >= 0) {

                        long seconds = (long) (millisUntilFinished / 1000);
                        long minutes = (long) ((millisUntilFinished / 1000) / 60);
                        long hours = (long) (((millisUntilFinished / 1000) / 60) / 60);

                        // Do some formatting to make seconds, minutes and hours look pretty    

                        // Update the timer TextView     
                        ((TextView) findViewById(R.id.CountDownTimerTextView))
                                .setText(hours + ":" + minutes + ":"
                                        + seconds);
                        }
                    }

    });
    // Other code
    ...
}
3
  • 1
    That's indeed what I meant by using only one thread for the clock and let all time logic depend on it. Your hack might come from the fact that the ChronometerListener is called when you call start() on the chronometer. The documentation about this listener is quite incomplete and your code assumes its called every second but it could be called more often, you might want to test outside this code when it is really called.
    – jolivier
    Commented Nov 21, 2012 at 8:50
  • Wow! Thank you. I'm grateful for your suggestion and happy that the implementation is more or less what you meant. You're right about onChronometerTick - it looks like it's called two times - but only when mChronometer.start() is called. After that it seems to be called just once every second. Strange. I wonder what an elegant fix to this problem is.
    – aLearner
    Commented Nov 21, 2012 at 10:36
  • I started a new thread to focus on the two bugs that were encountered here. It looks like `onChronometerTick' may be to blame. For more details, please see stackoverflow.com/questions/13523804/…
    – aLearner
    Commented Nov 23, 2012 at 6:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.