说明:
CountDownTimer timer = new CountDownTimer(30000, 1000)中,第一个参数表示总时间,第二个参数表示间隔时间。
意思就是每隔一秒会回调一次方法onTick,然后30秒之后会回调onFinish方法。
package com.androidcountdowntimer2; import android.app.Activity; import android.os.Bundle; import android.os.CountDownTimer; import android.widget.TextView; /** * Android倒计时功能的实现(CountDownTimer) * @author zhongyao * */ public class MainActivity extends Activity { private MyCount mc; private TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (TextView)findViewById(R.id.show); mc = new MyCount(30000, 1000); mc.start(); } /*定义一个倒计时的内部类*/ class MyCount extends CountDownTimer { public MyCount(long millisInFuture, long countDownInterval) { super(millisInFuture, countDownInterval); } @Override public void onTick(long millisUntilFinished) { tv.setText("请等待:" + millisUntilFinished / 1000 + "秒..."); } @Override public void onFinish() { tv.setText("finish"); } } @Override protected void onDestroy() { super.onDestroy(); mc.cancel(); } }