定时执行在一段时候后停止的倒计时,在倒计时执行过程中会在固定间隔时间得到通知(译者:触发onTick方法),下面的例子显示在一个文本框中显示一个30s倒计时:
new CountdownTimer(30000, 1000) { public void onTick(long millisUntilFinished) { mTextField.setText("seconds remaining: " + millisUntilFinished / 1000); } public void onFinish() { mTextField.setText("done!"); } }.start();
构造函数
public CountDownTimer (long millisInFuture, long countDownInterval)
参数
millisInFuture 从开始调用start()到倒计时完成并onFinish()方法被调用的毫秒数。(译者注:倒计时时间,单位毫秒)
countDownInterval 接收onTick(long)回调的间隔时间。(译者注:单位毫秒)
公共方法
public final void cancel ()
取消倒计时(译者:取消后,再次启动会重新开始倒计时)
public abstract void onFinish ()
倒计时完成时被调用
public abstract void onTick (long millisUntilFinished)
固定间隔被调用
参数
millisUntilFinished 倒计时剩余时间。
public synchronized final CountDownTimer start ()
启动倒计时
import android.app.Activity; import android.os.Bundle; import android.os.CountDownTimer; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import com.test.R; public class CountDownTimeActivity extends Activity implements OnClickListener { TextView mTextView; Button mButton1; Button mButton2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.countdown); mTextView = (TextView)findViewById(R.id.textView1); mButton1 = (Button)findViewById(R.id.button1); mButton2 = (Button)findViewById(R.id.button2); mButton1.setOnClickListener(this); mButton2.setOnClickListener(this); } CountDownTimer timer = new CountDownTimer(40000,1000) { @Override public void onTick(long millisUntilFinished) { mTextView.setText("seconds remaining: " + millisUntilFinished / 1000); try { Thread.sleep(1200); } catch (InterruptedException e) { e.printStackTrace(); } Log.e("CountDown",millisUntilFinished+""); } @Override public void onFinish() { mTextView.setText("done!"); } }; @Override public void onClick(View v) { switch(v.getId()){ case R.id.button1: timer.start(); break; case R.id.button2: timer.cancel(); break; } } }
[Android Pro] CountDownTimer倒计时
原文:http://www.cnblogs.com/0616--ataozhijia/p/5202247.html