Android实现倒计时两种方式

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
timecount.cancel();

RxAndroid 倒计时

  • 定义一个subscriber
private Subscriber subscriber;
  • 在请求接口成功后开始订阅
private void Test() {
        final int count = 60;
        Observable ob = Observable.interval(1, TimeUnit.SECONDS)
                .take(count)
                .map(new Func1() {
                    @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() {
            @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();

你可能感兴趣的:(Android实现倒计时两种方式)