在我们购物的时候会用到支付倒计时这个功能,其实Android已经帮封装好了一个类 CountDownTimer。
在一个TextView中不断显示剩下的时间,代码如下:
private TextView mTvSurplusTime;
private CountDownTimer timer = new CountDownTimer(20*60*1000,1000) {
@Override
public void onTick(long millisUntilFinished) {
long minute = millisUntilFinished/(60*1000);
long second=(millisUntilFinished-minute*60*1000)/1000;
String convertTime=minute+"分"+second+"秒";
mTvSurplusTime.setText("支付剩余时间"+convertTime);
}
@Override
public void onFinish() {
Util.showToast("20分钟已到,请重新下单",mContext);
finish();
}
};
调用的时候很简单:timer.start();
在CountDownTimer timer = new CountDownTimer(20*60*1000,1000)中,第一个参数表示总时间,第二个参数表示间隔时间。意思就是每隔一秒会回调一次方法onTick,然后20分钟之后会回调onFinish方法。
下面是CountDownTimer的源码,从源码可以发现,CountDownTimer也是基于Handler进行处理的:
packageandroid.os;
/**
* Schedule a countdown until a time in the future, with
* regular notifications on intervals along the way.