Search This Blog

Saturday, April 13, 2013

Count Down Timer in android

Android provide a android.os.CountDownTimer. By new a CountDownTimer object, and overriding the call-back function onTick() and onFinish(), you can implement a count down timer easily.

public class CountDownTimerActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
                           super.onCreate(savedInstanceState);
                           setContentView(R.layout.main);

                final TextView myCounter = (TextView)findViewById(R.id.mycounter);
                new CountDownTimer(30000, 1000) {

                                        @Override
                                        public void onFinish() {
                                                         // TODO Auto-generated method stub
                                                         myCounter.setText("completed Timer!");
                                        }

                                       @Override
                                        public void onTick(long millisUntilFinished) {
                                                    // TODO Auto-generated method stub
                                                   myCounter.setText("Millisecond Until Finished: " + String.valueOf(millisUntilFinished));
                                       }

                   }.start(); 
       } 
}

Xml file will be below.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<TextView
android:id="@+id/mycounter"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />

</LinearLayout>