private long mHour = 02; private long mMin = 15; private long mSecond = 36; private boolean isRun = true; String hourStr; String minuteStr; String secondStr;
/**
* 开启倒计时
*/
private void startRun() {
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while (isRun) {
try {
Thread.sleep(1000); // sleep 1000ms
Message message = Message.obtain();
message.what = 1;
timeHandler.sendMessage(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).start();
}
/**
* 倒计时计算
*/
private void computeTime() {
mSecond--;
if (mSecond < 0) {
mMin--;
mSecond = 59;
if (mMin < 0) {
mMin = 59;
mHour--;
}
}
}
发送消息给Handler:
private Handler timeHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what==1) {
computeTime();
if (mHour<10){
hourStr="0"+mHour+"";
}else {
hourStr="0"+mHour+"";
}
if (mMin<10){
minuteStr=mMin+"";
}else {
minuteStr=mMin+"";
}
if (mSecond<10){
secondStr="0"+mSecond+"";
}else {
secondStr=mSecond+"";
}
}
tv.setText("倒计时:"+hourStr+"小时"+minuteStr+"分钟"+secondStr+"秒");
}
};