How to set CountDownTimer in android

Count Down Timer usually helpful for timing the approach time to a particular event. In this example showing a 15-second countdown timer with regular notifications on intervals along the way.

The App looks Like

Github: https://github.com/rincemathew/CountdownTimer

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:gravity="center"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/timer"
        android:textSize="30dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {


    TextView timer;

    //timer time = 15 sec
    MyCountDownTimer firstTimer = new MyCountDownTimer(15000,1000);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        timer=findViewById(R.id.timer);

        //start the timer
        firstTimer.start();


    }

    public class MyCountDownTimer extends CountDownTimer {
        public MyCountDownTimer(long startTime, long interval) {
            super(startTime, interval);
        }
        @Override
        public void onFinish() {
            //what happens when the timer is finish
            Toast.makeText(getApplicationContext(),"finish",Toast.LENGTH_SHORT).show();
            firstTimer.start();
        }
        @Override
        public void onTick(long millisUntilFinished) {
            //what happens when the timer is running
            timer.setText("" + millisUntilFinished / 1000);

        }
        //always use this for stop the timer otherwise timer is running in the background
        //firstTimer.cancel();

    }
}

Keep exploring more tutorial from this site. In case of any queries make a comment. Happy coding!!!!

Add a Comment

Your email address will not be published. Required fields are marked *