Android: simple time counter

Chekout this example, that uses the Chronometer class: http://android-er.blogspot.com/2010/06/android-chronometer.html

Using the Chronometer class will save you managing the thread yourself.


This way it is much simpler. It is a feature made available on the android developer site. Link

public void initCountDownTimer(int time) {
    new CountDownTimer(30000, 1000) {

        public void onTick(long millisUntilFinished) {
            textView.setText("seconds remaining: " + millisUntilFinished / 1000);
        }

        public void onFinish() {
            textView.setText("done!");
        }
    }.start();
}

Kotlin Version

fun initCountDownTimer(time: Int) {
object : CountDownTimer(30000, 1000) {
    override fun onTick(millisUntilFinished: Long) {
        textView.setText("seconds remaining: " + millisUntilFinished / 1000)
    }

    override fun onFinish() {
        textView.setText("done!")
    }
}.start()

}


Perfect solution if you want to display running clock.

private void startClock(){
    Thread t = new Thread() {

        @Override
        public void run() {
            try {
                while (!isInterrupted()) {
                    Thread.sleep(1000);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Calendar c = Calendar.getInstance();

                            int hours = c.get(Calendar.HOUR_OF_DAY);
                            int minutes = c.get(Calendar.MINUTE);
                            int seconds = c.get(Calendar.SECOND);

                            String curTime = String.format("%02d  %02d  %02d", hours, minutes, seconds);
                            clock.setText(curTime); //change clock to your textview
                        }
                    });
                }
            } catch (InterruptedException e) {
            }
        }
    };

    t.start();
}

You can introduce flag. Something like isPaused. Trigger this flag whenever 'Pause' button pressed. Check flag value in your timer task. Success.

Timer T=new Timer();
T.scheduleAtFixedRate(new TimerTask() {         
        @Override
        public void run() {
            runOnUiThread(new Runnable()
            {
                @Override
                public void run()
                {
                    myTextView.setText("count="+count);
                    count++;                
                }
            });
        }
    }, 1000, 1000);


 onClick(View v)
 {
      //this is 'Pause' button click listener
      T.cancel();
 }

Tags:

Timer

Android