user3152651 user3152651 - 4 months ago 36
Android Question

Custom Count Up Timer

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:

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

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();
Comments