private int minute = 1;//这是分钟
private int second = 0;//这是分钟后面的秒数。这里是以30分钟为例的,所以,minute是30,second是0
private TextView tvname;
private Timer timer;
private TimerTask timerTask;
//这是接收回来处理的消息
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (minute == 0) {
if (second == 0) {
tvname.setText("结束");
if (timer != null) {
timer.cancel();
timer = null;
}
if (timerTask != null) {
timerTask = null;
}
} else {
second--;
if (second >= 10) {
tvname.setText("0" + minute + ":" + second);
} else {
tvname.setText("0" + minute + ":0" + second);
}
}
} else {
if (second == 0) {
second = 59;
minute--;
if (minute >= 10) {
tvname.setText(minute + ":" + second);
} else {
tvname.setText("0" + minute + ":" + second);
}
} else {
second--;
if (second >= 10) {
if (minute >= 10) {
tvname.setText(minute + ":" + second);
} else {
tvname.setText("0" + minute + ":" + second);
}
} else {
if (minute >= 10) {
tvname.setText(minute + ":0" + second);
} else {
tvname.setText("0" + minute + ":0" + second);
}
}
}
}
}
};
//在oncreate中
tvname = (TextView) findViewById(R.id.tvname);
if (minute == 0 && second == 30) {
tvname.setText("" + minute + ":" + second);
tvname.setTextColor(getResources().getColor(R.color.red));
} else {
tvname.setText(minute + ":" + second);
}
timerTask = new TimerTask() {
@Override
public void run() {
Message msg = new Message();
msg.what = 0;
handler.sendMessage(msg);
}
};
timer = new Timer();
timer.schedule(timerTask, 0, 1000);
}
@Override
protected void onDestroy() {
if (timer != null) {
timer.cancel();
timer = null;
}
if (timerTask != null) {
timerTask = null;
}
minute = -1;
second = -1;
super.onDestroy();
}