1、方法一:
利用CountDownTimer类
//这个方法中的两个参数第一个是 倒计时的时长,第二个是每次减少的时间
CountDownTimer timer = new CountDownTimer(5000,1000) {
@Override
public void onTick(long millisUntilFinished) {
//donghua_textview展示数据的控件
donghua_textview.setText(millisUntilFinished/1000+"S");
}
//动画结束时调用的方法
@Override
public void onFinish() {
startActivity(new Intent(DonghuaActivity.this, LoginActivity.class));
}
};
//最后不要忘记调用start();方法
timer.start();
2、方法二:
//利用Timer类
int mSeconds = 5;
Timer timer = new Timer();
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 1) {
if (mSeconds == 0) {
timer.cancel();
startActivity(new Intent(DonghuaActivity.this, LoginActivity.class));
} else if (mSeconds > 0) {
donghua_textview.setText(mSeconds + "S");
}
}
}
};
TimerTask task = new TimerTask() {
@Override
public void run() {
mSeconds--;
handler.sendEmptyMessage(1);
}
};
//调用timer类中的schedule方法
timer.schedule(task, 1000, 1000);
3、方法三:
利用handler发送延迟线程
int mSeconds = 5;
Handler handler = new Handler();
private void changeSeconds() {
mSeconds--;
handler.postDelayed(new Runnable() {
@Override
public void run() {
main_textview.setText(mSeconds+"S");
if(mSeconds==0){
//在这里我们开启动画不做跳转
initDonghua();
}else{
changeSeconds();
}
}
},1000);
}
//初始化动画
private void initDonghua() {
Animation animation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.anim);
animation.setAnimationListener(this);
main_textview.startAnimation(animation);
}
private void initView() {
main_textview = (TextView) findViewById(R.id.main_textview);
}
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
//在动画结束的时候进行跳转
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
}
@Override
public void onAnimationRepeat(Animation animation) {
}