比如某一商家搞活动需要用到倒计时功能,用Android代码简单实现其实就是用到了计时器类(Timer),主要算法封装在日期工具类里了。
1、算法
/**
* me.tongleer.com
* 通过秒格式化时间
* @param s
* @return
*/
public static String formatTimeBySecond(Integer s) {
int hour = 0;
int minute = 0;
int second = 0;
second = s;
if (second > 60) {
minute = second / 60;
second = second % 60;
}
if (minute > 60) {
hour = minute / 60;
minute = minute % 60;
}
String strtime = hour+":"+minute+":"+second;
return strtime;
}
2、倒计时方法
private void countDown(){
tvTime.setText("距离结束\n"+DateUtil.formatTimeBySecond(second));
timer = new Timer();
TimerTask task=new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
tvTime.setText("距离结束\n"+DateUtil.formatTimeBySecond(second));
if(second<=0){
timer.cancel();
}
second--;
}
});
}
};
timer.schedule(task, 1000, 1000);
}
下载链接:http://pan.baidu.com/s/1c2cF0XE
密码:g7gj