- new CountdownTimer(30000, 1000) {
- public void onTick(long millisUntilFinished) {
- mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
- }
- public void onFinish() {
- mTextField.setText("done!");
- }
- }.start();
new CountdownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
- package cn.demo;
- import android.app.Activity;
- import android.os.Bundle;
- import android.content.Intent;
- import android.os.CountDownTimer;
- import android.widget.TextView;
- import android.widget.Toast;
- public class NewActivity extends Activity {
- private MyCount mc;
- private TextView tv;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- // TODO Auto-generated method stub
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- tv = (TextView)findViewById(R.id.show);
- mc = new MyCount(30000, 1000);
- mc.start();
- }//end func
- /*定义一个倒计时的内部类*/
- class MyCount extends CountDownTimer {
- public MyCount(long millisInFuture, long countDownInterval) {
- super(millisInFuture, countDownInterval);
- }
- @Override
- public void onFinish() {
- tv.setText("finish");
- }
- @Override
- public void onTick(long millisUntilFinished) {
- tv.setText("请等待30秒(" + millisUntilFinished / 1000 + ")...");
- Toast.makeText(NewActivity.this, millisUntilFinished / 1000 + "", Toast.LENGTH_LONG).show();//toast有显示时间延迟
- }
- }
- }
package cn.demo;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.os.CountDownTimer;
import android.widget.TextView;
import android.widget.Toast;
public class NewActivity extends Activity {
private MyCount mc;
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)findViewById(R.id.show);
mc = new MyCount(30000, 1000);
mc.start();
}//end func
/*定义一个倒计时的内部类*/
class MyCount extends CountDownTimer {
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onFinish() {
tv.setText("finish");
}
@Override
public void onTick(long millisUntilFinished) {
tv.setText("请等待30秒(" + millisUntilFinished / 1000 + ")...");
Toast.makeText(NewActivity.this, millisUntilFinished / 1000 + "", Toast.LENGTH_LONG).show();//toast有显示时间延迟
}
}
}
主要是重写onTick和onFinsh这两个方法,onFinish()中的代码是计时器结束的时候要做的事情;onTick(Long m)中的代码是你倒计时开始时要做的事情,参数m是直到完成的时间,构造方法MyCount()中的两个参数中,前者是倒计的时间数,后者是倒计每秒中间的间隔时间,都是以毫秒为单位。例如要倒计时30秒,每秒中间间隔时间是1秒,两个参数可以这样写MyCount(30000,1000)。 将后台线程的创建和Handler队列封装成为了一个方便的类调用。
当你想取消的时候使用mc.cancel()方法就行了。