What is the usage of CountDownTimer in Android?
In Android, the CountDownTimer class is used to create a countdown timer. This class allows us to perform operations at specified intervals of time, such as updating the UI interface every second or executing other actions. Here is a basic example of how to use the CountDownTimer class:
- Create a CountDownTimer object and implement its onTick and onFinish methods.
CountDownTimer timer = new CountDownTimer(60000, 1000) {
public void onTick(long millisUntilFinished) {
// 每隔一秒执行的操作
textView.setText("剩余时间:" + millisUntilFinished / 1000 + "秒");
}
public void onFinish() {
// 倒计时结束时执行的操作
textView.setText("倒计时结束");
}
};
- The countdown begins.
timer.start();
In the example above, we set up a 60-second countdown that updates a TextView every second to display the remaining time. When the countdown reaches zero, the TextView will display “Countdown Finished.”
It is important to note that the CountDownTimer constructor takes two parameters: the total countdown time (in milliseconds) and the interval between each invocation of the onTick method (in milliseconds). The onTick method can be used to perform operations that need to be repeated, while the onFinish method is used to execute operations after the countdown has finished.