Custom Count Up Timer

Rambod Ghasemi picture Rambod Ghasemi · Jan 28, 2016 · Viewed 10.2k times · Source

I need a count up timer in my application. I browsed many forums about this subject, but I could not find anything. Actually I understood we can do this with chronometer, but I have 2 problem with chronometer:

  1. I cannot using chronometer in Service because chronometer needs a layout.
  2. I cannot initialize chronometer to count more than 1 hour.

My code is here:

stopWatch =  new Chronometer (MainActivity.this);
startTime = SystemClock.elapsedRealtime();
stopWatch.start();
stopWatch.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
    @Override
    public void onChronometerTick(Chronometer arg0) {
        countUp = (SystemClock.elapsedRealtime() - arg0.getBase()) / 1000;
        String asText = (countUp / 60) + ":" + (countUp % 60);
        Log.i("t", asText);
    }
});

Answer

Uma Kanth picture Uma Kanth · Jan 28, 2016

You can use a countDownTimer in reverse and get the time elapsed.

long totalSeconds = 30;
long intervalSeconds = 1;

CountDownTimer timer = new CountDownTimer(totalSeconds * 1000, intervalSeconds * 1000) {

    public void onTick(long millisUntilFinished) {
        Log.d("seconds elapsed: " , (totalSeconds * 1000 - millisUntilFinished) / 1000);
    }

    public void onFinish() {
        Log.d( "done!", "Time's up!");
    }

};

To start the timer.

timer.start();

To stop the timer.

timer.cancel();