版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_30552993/article/details/80959569
最近做一个商城,有个抢购的功能,所以就写了个时间戳之间的倒计时工具类,其实也蛮简单的,不过还是要贴出来给一些有兴趣的小伙伴看看。
其中主要用到Android提供了CountDownTimer倒计时类
public CountDownTimer(long millisInFuture, long countDownInterval){}
参数1,设置倒计时的总时间(毫秒)
参数2,设置间隔时长(毫秒)
其中对应有两个方法:
//每间隔countDownInterval调用一次,millisUntilFinished表示还剩多少毫秒
public abstract void onTick(long millisUntilFinished);
//倒计时结束时执行
public abstract void onFinish();
开始跟取消,对应的调用方式:
CountDownTimer timer=....;
//开始倒计时
timer.start()
//取消倒计时
timer.cancel()
//在宿主Activity或fragment生命周期结束时,记得调用timer.cancle()方法
@Override
public void onDestroy() {
if(timer!=null){
timer.cancel();
timer = null;
}
super.onDestroy();
}
进入正题, 时间戳之间的倒计时工具类
public class CountDownUtil {
private CountDownTimer mTimer;
private int interval = 1000;
public CountDownUtil() {
}
/**
* 日期转时间戳
*
* @param date
* @param format
* @return
*/
public static long getTimeStamp(String date, String format) {
return DateUtil.strToDate(date, format).getTime();
}
/**
* 开始倒计时
*
* @param startTime 开始时间(时间戳)
* @param minuteInterval 时间间隔(单位:分)
* @param callBack
*/
public void start(long startTime, int minuteInterval, OnCountDownCallBack callBack) {
long lengthTime = minuteInterval * 60 * interval;
//查看是否为毫秒的时间戳
boolean isMillSecond = (String.valueOf(startTime).length() == 13);
startTime = startTime * (isMillSecond ? 1 : interval);
long endTime = startTime + lengthTime;
long curTime = System.currentTimeMillis();
mTimer = getTimer(endTime - curTime, interval, callBack);
if (Math.abs(curTime - startTime) > lengthTime) {
if (callBack != null) {
callBack.onFinish();
}
} else {
mTimer.start();
}
}
private CountDownTimer getTimer(long millisInFuture, long interval, OnCountDownCallBack callBack) {
return new CountDownTimer(millisInFuture, interval) {
@Override
public void onTick(long millisUntilFinished) {
int day = 0;
int hour = 0;
int minute = (int) (millisUntilFinished / interval / 60);
int second = (int) (millisUntilFinished / interval % 60);
if (minute > 60) {
hour = minute / 60;
minute = minute % 60;
}
if (hour > 24) {
day = hour / 24;
hour = hour % 24;
}
if (callBack != null) {
callBack.onProcess(day, hour, minute, second);
}
}
@Override
public void onFinish() {
if (callBack != null) {
callBack.onFinish();
}
}
};
}
/**
* 开始倒计时
*
* @param endTime 结束时间(时间戳)
* @param callBack
*/
public void start(long endTime, OnCountDownCallBack callBack) {
long curTime = System.currentTimeMillis();
mTimer = getTimer(endTime - curTime, interval, callBack);
if (endTime < curTime) {
if (callBack != null) {
callBack.onFinish();
}
} else {
mTimer.start();
}
}
/**
* 必用
*/
public void onDestroy() {
if (mTimer != null) {
mTimer.cancel();
mTimer = null;
}
}
public interface OnCountDownCallBack {
void onProcess(int day, int hour, int minute, int second);
void onFinish();
}
}