The foundation of Android-CountDownTimer class for easy countdown
Before discovering this class, I used handler, subthread to send messages, and UI thread to display the countdown. I found this class when I made a countdown display a few days ago, which is very convenient to use.
After reading the source code, we have implemented handler sub-thread operations internally.
The CountDownTimer class is easy to use. You can use the following code for two parameters:
<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHByZSBjbGFzcz0 = "brush: java;"> CountDownTimer (long millisInFuture, long countDownInterval)
The constructor has two parameters: the first millisInFuture refers to the total time for countdown, the unit is long MS, and the second parameter countDownInterval refers to the countdown frequency, is it a countdown of 1 s or a countdown of 2 s
It is easy to understand the meaning of these two parameters. A new CountDownTimer object will generate two callback functions.
public void onTick(long millisUntilFinished) {// TODO Auto-generated method stub}@Overridepublic void onFinish() {// TODO Auto-generated method stub}
The first method is called during the countdown. You can put the operations to be performed every time the countdown is performed. Generally, some operations are performed on the UI thread, for example, you can change the text to achieve the countdown effect.
The second method is called after the countdown is complete. You can write all the operations required to complete the countdown.
Of course, remember to start () in the end, otherwise the thread will not start
All code:
Public class MainActivity extends Activity {private TextView TV; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); TV = (TextView) findViewById (R. id. TV);/** countdown 60 seconds, 1 second at a time */CountDownTimer timer = new CountDownTimer (60*1000,100 0) {@ Overridepublic void onTick (long millisUntilFinished) {// TODO Auto-generated method stubtv. setText ("remaining" + millisUntilFinished/1000 + "seconds");} @ Overridepublic void onFinish () {TV. setText ("Countdown finished ");}}. start ();}}
: