今天正好要用到获取验证码的功能,要60秒内不能再次获取,原来想用Handler和timer来实现,结果发现有一个新的类竟然这么好用,而且没有用过!
private CountDownTimer timer = new CountDownTimer(codeSpaceTime, 1000) {
@Override
public void onTick(long millisUntilFinished) {
getPhoneCodeTv.setEnabled(false);
getPhoneCodeTv.setText((millisUntilFinished / 1000) + "秒后可重发");
}
@Override
public void onFinish() {
getPhoneCodeTv.setEnabled(true);
getPhoneCodeTv.setText(R.string.register_get_ver_code);
}
};
codeSpaceTime 是间隔多少时间能够重新发送,我这里设置的是60秒;1000是刷新的频率这里是1秒钟刷新一次!
点击开始直接调用timer.start()方法即可;
if (checkPhone(phoneNum)) {
timer.start();
requestPhoneCode(phoneNum);
} else {
Toast.makeText(mContext, R.string.register_phone_not_right, Toast.LENGTH_LONG).show();
}
当然timer还有其他的方法:
timer.cancel();