user1209031
user1209031

Reputation: 179

How to add a Countup timer on Android?

I would like to add a timer for my Android Sudoku game. I need to know the source code and how to put the source code into my game.

Upvotes: 15

Views: 35151

Answers (8)

Konrad
Konrad

Reputation: 72

I spent few hours to find KISS solution for the Count Up Timer. If we use View Class to display the time definitely the easiest solution is to use Chronometer class.

Unfortunately, it does not work without the View. I wish to show the time in Action Bar that is why I needed the String with the time without the view. Here is my idea:

I am using java.util.Timer and java.util.TimerTask and Kotlin in Android Studio.

  private fun stopwatch() {
    var num : Long = 0L
    val timer : Timer = Timer()
    val tt : TimerTask = object : TimerTask(){
        override fun run() {
            num+=1000L
            println(TimerUtil.timerDisplay(num))
        }
    }
    timer.schedule(tt, 0L, 1000L)
}

The helper function to format the String to MM:SS format:

class TimerUtil {
companion object {
    fun timerDisplay(time: Long): String {
        val minutes = TimeUnit.MILLISECONDS.toMinutes(time)
        val seconds = TimeUnit.MILLISECONDS.toSeconds(time) - TimeUnit
            .MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time))

        return " %02d:%02d".format(minutes, seconds)
    }
}

}

Upvotes: 1

Ika
Ika

Reputation: 1748

For the sake of completion and because I had to do it. Here's a Kotlin version:

import android.os.CountDownTimer

abstract class CountUpTimer(private val secondsInFuture: Int, countUpIntervalSeconds: Int) : CountDownTimer(secondsInFuture.toLong() * 1000, countUpIntervalSeconds.toLong() * 1000) {

    abstract fun onCount(count: Int)

    override fun onTick(msUntilFinished: Long) {
        onCount(((secondsInFuture.toLong() * 1000 - msUntilFinished) / 1000).toInt())
    }
}

And here's how to use it

val counter = object: CountUpTimer(30, 1){
      
      override fun onCount(count: Int) {
          Log.i("Counter", "Counting: $count")
      }
                
      override fun onFinish() {
          Log.i("Counter", "Counting done")
      }
}
counter.start()

Upvotes: 2

Amos
Amos

Reputation: 2660

Layout XML:

<Chronometer
android:id="@+id/simpleChronometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

Code:

Chronometer simpleChronometer = (Chronometer) findViewById(R.id.simpleChronometer); // initiate a chronometer

simpleChronometer.start(); // start a chronometer

enter image description here

Upvotes: 22

Dan Andreasson
Dan Andreasson

Reputation: 16212

If you're on android and need a timer which ticks each second you can create the following subclass of CountDownTimer. It can easily be modified to tick at whatever interval you want.

import android.os.CountDownTimer;

public abstract class CountUpTimer extends CountDownTimer {
        private static final long INTERVAL_MS = 1000;
        private final long duration;

    protected CountUpTimer(long durationMs) {
        super(durationMs, INTERVAL_MS);
        this.duration = durationMs;
    }

    public abstract void onTick(int second);

    @Override
    public void onTick(long msUntilFinished) {
        int second = (int) ((duration - msUntilFinished) / 1000);
        onTick(second);
    }

    @Override
    public void onFinish() {
        onTick(duration / 1000);
    }
}

And then use it like

CountUpTimer timer = new CountUpTimer(30000) {
    public void onTick(int second) {
        timerView.setText(String.valueOf(second));
    }
};

timer.start();

Upvotes: 15

Miguel
Miguel

Reputation: 20143

I might be too late but what the hell. Here's a small example of how you could create a CountUpTimer. This code was inspired by CountDownTimer.

https://gist.github.com/MiguelLavigne/8809180c5b8fe2fc7403

Upvotes: 12

Lettings Mall
Lettings Mall

Reputation: 300

It turns out that chronometer uses something called system.elapsedRealTime internally which is the time from when the phone first booted.

In a practical situation on power down chonometers readings go wrong even if the trime is saved previously.

Upvotes: 1

ROHIT PARMAR
ROHIT PARMAR

Reputation: 931

_countTimer = new CountDownTimer(40000, 1000) {
            public void onTick(long millisUntilFinished) {
                String _millis=String.valueOf(40-(millisUntilFinished/1000));
                CameraScreen._timerTxt.setText("0."+_millis);
            }
 _countTimer.start();

Upvotes: 2

Ovidiu Latcu
Ovidiu Latcu

Reputation: 72331

Android's CountDownTimer should fit your needs. The documentation also provides a small example which will help you.

EDIT : for counting up I think Android's Chronometer will be the easiest choice.

EDIT2: I think you should start here.

Upvotes: 5

Related Questions