package com.bwei.timer;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
int time=3;
//创建Timer计时器
Timer timer = new Timer();
private TextView tv_time;
private Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
if(msg.what==0){
if(time==-1){
Toast.makeText(MainActivity.this, "倒计时结束", 0).show();
return;
}
tv_time.setText("倒计时:"+(time--)+"秒");
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_time = (TextView) findViewById(R.id.tv_time);
//执行计时任务
timer.schedule(new MyTimerTask(), 1000, 1000);
}
//定义TimerTask
private class MyTimerTask extends TimerTask{
Message message = handler.obtainMessage(0);
message.sendToTarget();
}
}
}
timer实现倒计时
最新推荐文章于 2019-10-05 11:40:48 发布