Snake
Snake

Reputation: 14668

Stop watch timer that increments (like countdowntimer)

I have been using countdowntimer and it has performed perfectly. Now I want to implement the opposite (Something like stop watch) in which the time updates the screen every second and it increments forever till I stop.

Is there a way (similar in simplicity) that does the job sort of like Countdowntimer? I know I can use Timer and Timertask but this creates new thread and I read that it is not that reliable (or recommended).

Thank you

Upvotes: 1

Views: 338

Answers (2)

user184994
user184994

Reputation: 18281

If you add the following class to you project, you can use it just like the CountDownTimer class:

public abstract class Stopwatch extends Thread {

    int tickFreq;


    public Stopwatch(int tickFreq) {
        this.tickFreq = tickFreq;
    }


    abstract void onTick();


    @Override
    public void run() {
        onTick();

        try {
            Thread.sleep(tickFreq);
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
        super.run();
    }

}

And to use it, you would write:

new Stopwatch(1000){

    @Override
    void onTick() {
        // Do whatever you want to do in here
    }

}.start();

The param that's passed to the constructor (1000) is how often it should call onTick(). In this case, it's every 1000 milliseconds, i.e. every 1 second.

Upvotes: 1

matiash
matiash

Reputation: 55370

Looks like a Chronometer object is what you need.

By setting a tick listener, you will get a tick every second (unfortunately that's the minimum precision available, but from the question it looks like it's enough for your needs).

Upvotes: 2

Related Questions