Saturday, October 4, 2014

Timer counter Logic



Timer counter logic

private TextView tvTimeCounter;
int hour, min, sec; // this all initiating with 0 by default;

Handler counterHandler = new Handler(); // Use handler for Runnable

// Counter Runnable which will called itself after 1 sec (Recursively)
Runnable counterRunnable = new Runnable(){
    @Override
        public void run() {
            if (sec == 59) {
                if (min == 59) {
                    hour++;
                    min = 0;
                } else {
                    min++;
                }
                sec = 0;
            } else {
                sec++;
            }

            updateTimer();
            counterHandler.postDelayed(this, 1000);
        }

}


// This method will be called every 1 sec and update your TextView with new time
public void updateTimer() {
        runOnUiThread(new Runnable() {
            public void run() {
                tvTimeCounter.setText(String.format("%02d:%02d:%02d", hour,
                        min, sec));

            }
        });
 


public void onCreate(Bundle bundle){
      super.onCreate(bundle);
      tvTimeCounter = new TextView();
      setContentView(tvTimeCounter);
}

public void onResume(){
     super.onResume();
     counterHandler.postDelay(counterRunnable); // on activity resume it will counter your counter
}

public void onPause(){
     super.onPause();
     counterHandler.removeCallback(counterRunnable); // on activity pause stop counter by removing handler
}



Just copy the above code and you have getting your Timer counter in Android

Happy to help you

No comments:

Post a Comment