android 的倒计时怎么做的,Android中的倒计时实现

public abstract classCountDownTimer {/*** Millis since epoch when alarm should stop.*/

private final longmMillisInFuture;/*** The interval in millis that the user receives callbacks*/

private final longmCountdownInterval;private longmStopTimeInFuture;/*** boolean representing if the timer was cancelled*/

private boolean mCancelled = false;/***@parammillisInFuture The number of millis in the future from the call

* to {@link#start()} until the countdown is done and {@link#onFinish()}

* is called.

*@paramcountDownInterval The interval along the way to receive

* {@link#onTick(long)} callbacks.*/

public CountDownTimer(long millisInFuture, longcountDownInterval) {

mMillisInFuture=millisInFuture;

mCountdownInterval=countDownInterval;

}/*** Cancel the countdown.*/

public synchronized final voidcancel() {

mCancelled= true;

mHandler.removeMessages(MSG);

}/*** Start the countdown.*/

public synchronized finalCountDownTimer start() {

mCancelled= false;if (mMillisInFuture <= 0) {

onFinish();return this;

}

mStopTimeInFuture= SystemClock.elapsedRealtime() +mMillisInFuture;

mHandler.sendMessage(mHandler.obtainMessage(MSG));return this;

}/*** Callback fired on regular interval.

*@parammillisUntilFinished The amount of time until finished.*/

public abstract void onTick(longmillisUntilFinished);/*** Callback fired when the time is up.*/

public abstract voidonFinish();private static final int MSG = 1;//handles counting down

private Handler mHandler = newHandler() {

@Overridepublic voidhandleMessage(Message msg) {synchronized (CountDownTimer.this) {if(mCancelled) {return;

}final long millisLeft = mStopTimeInFuture -SystemClock.elapsedRealtime();if (millisLeft <= 0) {

onFinish();

}else if (millisLeft

sendMessageDelayed(obtainMessage(MSG), millisLeft);

}else{long lastTickStart =SystemClock.elapsedRealtime();

onTick(millisLeft);//take into account user's onTick taking time to execute

long delay = lastTickStart + mCountdownInterval -SystemClock.elapsedRealtime();//special case: user's onTick took more than interval to//complete, skip to next interval

while (delay < 0) delay +=mCountdownInterval;

sendMessageDelayed(obtainMessage(MSG), delay);

}

}

}

};

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值