CountDownTimer倒计时
private static final long MILLIS_IN_FUTURE = 60000;
private static final long COUNT_DOWN_INTERVAL = 1000;
- 定义一个
TimeCount
类继承CountDownTimer
private class TimeCount extends CountDownTimer {
TimeCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onTick(long millisUntilFinished) {
if (mTvGetCode != null) {
mTvGetCode.setClickable(false);
String second = millisUntilFinished / 1000 + "秒";
mTvGetCode.setText(second);
}
}
@Override
public void onFinish() {
if (mTvGetCode != null) {
mTvGetCode.setText("获取验证码");
mTvGetCode.setClickable(true);
}
}
}
- new TimeCount并在请求接口成功后调用
start()
timecount = new TimeCount(MILLIS_IN_FUTURE, COUNT_DOWN_INTERVAL);
timecount.start();
timecount.cancel();
RxAndroid 倒计时
private Subscriber<Long> subscriber;
private void Test() {
final int count = 60;
Observable<Long> ob = Observable.interval(1, TimeUnit.SECONDS)
.take(count)
.map(new Func1<Long, Long>() {
@Override
public Long call(Long aLong) {
return count - aLong;
}
}).doOnSubscribe(new Action0() {
@Override
public void call() {
mTvGetCode.setClickable(false);
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
subscriber = new Subscriber<Long>() {
@Override
public void onNext(Long aLong) {
if (mTvGetCode != null) {
mTvGetCode.setText(aLong + "秒");
}
}
@Override
public void onCompleted() {
if (mTvGetCode != null) {
mTvGetCode.setText("获取验证码");
mTvGetCode.setClickable(true);
}
}
@Override
public void onError(Throwable e) {
}
};
ob.subscribe(subscriber);
}
subscriber.unsubscribe();