charles green
charles green

Reputation: 11

My timer start triggering faster and faster every time I start it again

It seems like there are multiple timers running together. I‘m calling this realTimer function each time a certain button is clicked. How do I solve it?

this is the code:

public void realTimer(){
        running = true;
        final Handler handler = new Handler();
        handler.post(new Runnable() {
            @Override
            public void run() {
                int hours = counter/3600;
                int minutes = (counter%3600)/60;
                int secs = counter%60;

                String time = String.format("%d:%02d:%02d", hours, minutes, secs);
                timerTextView.setText(time);

                if(running){
                    counter++;
                 }
                handler.postDelayed(this, 1000);
                }

        });
}

Upvotes: 1

Views: 42

Answers (1)

kboskin
kboskin

Reputation: 420

I think the code should be like this :

    //top level code
    final Handler handler = new Handler();
    //... other functions goes here
    public void realTimer(){
        running = true;
        counter = 0;
        handler.removeCallbacksAndMessages(null);

        Runnable callback =  new Runnable() {
            @Override
            public void run() {
                int hours = counter/3600;
                int minutes = (counter%3600)/60;
                int secs = counter%60;

                String time = String.format("%d:%02d:%02d", hours, minutes, secs);
                timerTextView.setText(time);

                if(running){
                    counter++;
                }
                handler.postDelayed(this, 1000);
            }

        };

        handler.post(callback);

}

The counter is set to 0 each time realTime() function is called, and callbacks are removed from the handler

Upvotes: 1

Related Questions