How to display the timer in android

rajeshlawrance picture rajeshlawrance · Jul 5, 2013 · Viewed 29.9k times · Source

I want to display the timer in TextView in the format of like [ 19:59].so when i click the start button ,the timer will display like this for example,i want to set upto 20 mintues,it will display like [19:58][19:87].can anyone give some ideas or example code?enter image description here

Answer

Raghunandan picture Raghunandan · Jul 5, 2013

You can use the CountDownTimer.

http://developer.android.com/reference/android/os/CountDownTimer.html

     TextView _tv = (TextView) findViewById( R.id.textView1 );
    new CountDownTimer(20*60000, 1000) {

        public void onTick(long millisUntilFinished) {
            _tv.setText("seconds remaining: " +new SimpleDateFormat("mm:ss:SS").format(new Date( millisUntilFinished)));
        }

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

To cancel just call cancel on the timer.

public final void cancel()

Cancel the countdown.