android如何写倒计时?
昨天开发了一个倒计时的功能,开始参考的是农民伯伯的算法,但是有误,且繁琐,因为我的项目中当前时间和截止时间都是从服务器上获取的,所以,以上方法并不太适合我,于是我写了一个更简单的方法,该方法的核心代码如下:
/* 主要的调用方法 */
TextView tableAlt;
int end;
int cur;
long mTimeDistance;
// 服务器上获取的当前时间
String currentTime = limited.getRec_datetime();
// 截止时间
String endTime = limits.get(0).getEndtime();
end = Integer.parseInt(endTime) * 1000;
cur = Integer.parseInt(currentTime) * 1000;
mTimeDistance = end - cur;
if (mTimeDistance <= 0) {
tableAlt.setText("活动结束");
} else {
handler.postDelayed(runnable, 1000);
}
/* handler的代码 */
Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
if (mTimeDistance <= 0) {
tableAlt.setText("活动结束");
} else {
int deadDays = getDeadDays(mTimeDistance);
int deadHour = getDeadHour(mTimeDistance);
int deadMinute = getDeadMinute(mTimeDistance);
int deadMills = getDeadMills(mTimeDistance);
String hour = "";
String minute = "";
String mills = "";
if (deadHour < 10) {
hour = "0" + deadHour;
} else {
hour = "" + deadHour;
}
if (deadMinute < 10) {
minute = "0" + deadMinute;
} else {
minute = "" + deadMinute;
}
if (deadMills < 10) {
mills = "0" + deadMills;
} else {
mills = "" + deadMills;
}
String deadTimeStr = "( 倒计时 " + deadDays + "天" + hour + ":"
+ minute + ":" + mills + ")";
// add end by fly
tableAlt.setText(deadTimeStr);
mTimeDistance = mTimeDistance - 1000;
handler.postDelayed(this, 1000);
}
}
};
/* 计算时间的方法 */
private int getDeadDays(long timeDistance) {
return (int) (timeDistance / (24 * 60 * 60 * 1000));
}
private int getDeadHour(long timeDistance) {
int hour = (int) (timeDistance % (24 * 60 * 60 * 1000))
/ (60 * 60 * 1000);
return hour;
}
private int getDeadMinute(long timeDistance) {
int minute = 0;
minute = (int) (timeDistance % (24 * 60 * 60 * 1000)) % (60 * 60 * 1000)
/ (60 * 1000);
return minute;
}
private int getDeadMills(long timeDistance) {
int mills = (int) (timeDistance % (24 * 60 * 60 * 1000))
% (60 * 60 * 1000) % (60 * 1000) / 1000;
return mills;
}
最后的运行效果:( 倒计时 0天06:42:54 ),并在不停地倒计时中。