抽象类CountDownTimer使用

最近在项目中需要在TextView中显示一个倒计时的功能,主要用到CountDownTimer抽象类。

使用该类需要给定两个时间,构造方法为:

public CountDownTimer(long millisInFuture, long countDownInterval){}

millisInFuture:该变量表示从调用start()方法开始,到onFinish()方法被回调共倒计时多少时间。

countDownInterval:时间间隔。

这两个变量的单位都是毫秒。

通过调用start()方法开始倒计时,源码如下:

public synchronized final CountDownTimer start() {
        mCancelled = false;
        if (mMillisInFuture <= 0) {
            onFinish();
            return this;
        }
        mStopTimeInFuture = SystemClock.elapsedRealtime() + mMillisInFuture;
        mHandler.sendMessage(mHandler.obtainMessage(MSG));
        return this;
    }
从源码中可看到是通过Handler来发送消息。

通过调用cancel()方法结束倒计时,源码如下:

public synchronized final void cancel() {
        mCancelled = true;
        mHandler.removeMessages(MSG);
    }
通过Handler将消息从消息队列中移除。

其实CountDownTimer只是对Handler进行了封装,追根究底还是使用了异步消息处理机制。

我们可自定义类继承CountDownTimer类,实现onTick()和onFinish()方法来实现在倒计时过程中对UI的操作。如:

    private class MyCountDownTimer extends CountDownTimer {
        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            mSendCaptcha.setText("(" + millisUntilFinished / 1000 + "s)" );
            setSendButton(false);
        }

        @Override
        public void onFinish() {
            mSendCaptcha.setText(R.string.regain_captch_text);
            setSendButton(true);
        }
    }




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值