Count up timer on Android?

4.9k views Asked by At

I've been looking for a way to create a timer that counts up in the format of mm:ss:SS and cannot for the life of me find a way of doing it. I had a timer running through a Handler and a Runnable but the timing was off and it took around 2.5 seconds to do a "second". I'll also need this timer be able to countdown too!

Can anyone give me any resources or code snippets to research on this as it is a big part of the app I'm coding.

Here's a bit of the code that I was using

private Handler handler = new Handler();

private Runnable runnable = new Runnable() {
       @Override
        public void run() {
      /* do what you need to do */
            testMethod();
      /* and here comes the "trick" */
            handler.postDelayed(this, 10);
        }
    };

public void testMethod()
    {
//        Log.d("Testing", "Test");
        final TextView timeLabel = (TextView)findViewById(R.id.timeString);
        count++;

        seconds = (int)(count / 100);

        final String str = ""+count;
        runOnUiThread(new Runnable() {
            public void run() {
                timeLabel.setText("" + seconds);
//                Log.d("Time", "" + count);
            }
        });
    }

Ta!

2

There are 2 answers

0
Pratyush Yadav On

Rather than using the Handler, I'd recommend using the java.util.Timer and the java.util.TimerTask APIs. Use the Timer's void scheduleAtFixedRate() method which basically executes tasks after a fixed interval of time. The Handler's method most likely uses a fixed-delay execution.

Timer's Documentation

TimerTask's Documentation

0
Vaygeth On

Make small custom class by extending CountDownTimer class and then add integer or long type and then increment it, since each tick is 1 second (integer) in this case

public class TimeCounter extends CountDownTimer {
    // this is my seconds up counter
    int countUpTimer;
    public TimeCounter(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
        countUpTimer=0;
    }

    @Override
    public void onTick(long l) {
        //since each tick interval is one second
        // just add 1 to this each time
        myTextView.setText("Seconds:"+countUpTimer);
        countUpTimer = countUpTimer+1;
    }

    @Override
    public void onFinish() {
        //reset counter to 0 if you want
        countUpTimer=0;           
    }
}

  TimeCounter  timer = new TimeCounter(whenToStopInSeconds*1000, 1000);

This should get you started, in your case use long instead integer countUpTimer = countUpTimer+1000 countUpTimer type and do time parsing as suits you