Stopwatch on Android

Question:

Good afternoon. Resumed studying the android platform. The following question arose. There are two pieces of code, here's the first one:

    public void runTimer(){
    final Handler handler = new Handler();
    final TextView timerView = (TextView)findViewById(R.id.time_view);

    handler.postDelayed(new Runnable(){

        @Override
        public void run() {
            int hours = seconds%3600;
         int minutes = (seconds%3600)%60;
         int secs = seconds%60; 
            String time = String.format("%d:%02d:%02d",hours,minutes,secs);
            timerView.setText(time);
            if(isStarting){
                seconds++;
            }   
        }

    }, 1000);

}

and here is the second one:

    public void runTimer(){
    final TextView timerView = (TextView)findViewById(R.id.time_view);
    final Handler  handler = new Handler();
    handler.post(new Runnable(){
        public void run(){
            int hours = seconds%3600;
             int minutes = (seconds%3600)%60;
             int secs = seconds%60; 
                String time = String.format("%d:%02d:%02d",hours,minutes,secs);
                timerView.setText(time);
                if(isStarting){
                    seconds++;
                }   
        handler.postDelayed(this, 1000);
        }
    });
}

The problem is that they should, as I understand it, work the same way, but only example number 2 works. Who knows why?

Answer:

1 piece of code is called exactly 1 time. It is called after 1 second using handler.postDelayed(..., 1000) , and that's it.

2 the code snippet is called immediately by the handler.post method and at the end of its work it calls handler.postDelayed(this, 1000); those. calls to itself after 1 second.

In general, I recommend looking at the CountDownTimer class, which basically does the same thing, but out of the box.

Scroll to Top