Android中的倒計時實現

來源:互聯網
上載者:User

標籤:

一、android.os包下提供了倒計時的抽象工具類:

public abstract class CountDownTimer {    /**     * Millis since epoch when alarm should stop.     */    private final long mMillisInFuture;    /**     * The interval in millis that the user receives callbacks     */    private final long mCountdownInterval;    private long mStopTimeInFuture;    /**     * boolean representing if the timer was cancelled     */    private boolean mCancelled = false;    /**     * @param millisInFuture The number of millis in the future from the call     *   to {@link #start()} until the countdown is done and {@link #onFinish()}     *   is called.     * @param countDownInterval The interval along the way to receive     *   {@link #onTick(long)} callbacks.     */    public CountDownTimer(long millisInFuture, long countDownInterval) {        mMillisInFuture = millisInFuture;        mCountdownInterval = countDownInterval;    }    /**     * Cancel the countdown.     */    public synchronized final void cancel() {        mCancelled = true;        mHandler.removeMessages(MSG);    }    /**     * Start the countdown.     */    public synchronized final CountDownTimer 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.     * @param millisUntilFinished The amount of time until finished.     */    public abstract void onTick(long millisUntilFinished);    /**     * Callback fired when the time is up.     */    public abstract void onFinish();    private static final int MSG = 1;    // handles counting down    private Handler mHandler = new Handler() {        @Override        public void handleMessage(Message msg) {            synchronized (CountDownTimer.this) {                if (mCancelled) {                    return;                }                final long millisLeft = mStopTimeInFuture - SystemClock.elapsedRealtime();                if (millisLeft <= 0) {                    onFinish();                } else if (millisLeft < mCountdownInterval) {                    // no tick, just delay until done                    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);                }            }        }    };}

 

二、一個Demo,用倒計時不斷重新整理剩餘時間,倒計時結束後置button為可點擊狀態


private class TimeCount extends CountDownTimer {    public TimeCount(long millisInFuture, long countDownInterval) {        super(millisInFuture, countDownInterval);    }    /**     * 計時過程中觸發     */    @Override    public void onTick(long millisUntilFinished) {        if (mVerify != null) {            int second = (int) (millisUntilFinished / 1000);  //計算出還剩多少秒            mVerify.setText(getString(R.string.main_control_panel_grab_count_down, second));         }    }    /**     * 計時完成時觸發     */    @Override    public void onFinish() {        isVerifing = false;        if (mVerify != null) {            mVerify.setEnabled(true);            mVerify.setText(R.string.register_verify);        }    }}

 




三、注意:

1. 該種方式實現的倒計時考慮了每次onTick處理函數中耗費的時間。
2. 使用的是handler機制,因此預設是靠Ui線程處理處理onTick函數(onTick中很可能有更新Ui的操作)
3. 可以看出,”迴圈“也是靠handleMessage方法中再拋一個Message方式實現(插一句話,常見的迴圈可以通過)。
4. 還有一點值得注意的是,每次onTick時,傳入的是剩餘時間值。
5. handleMessage方法的實現細節:
分兩種情況:
1) onTick()的處理時間小於一個mCountdownInterval,所以delay(delay = lastTickStart + mCountdownInterval - SystemClock.elapsedRealtime())時間後正好是下一個onTick()時刻。
     

2)  onTick()的處理時間大於或等於一個mCountdownInterval,不妨假設大於2個mCountdownInterval,則經過while迴圈不斷跳過onTick()過程中耽擱的mCountdownInterval後,直到delay大於0時,正好是"下一個"mCountdownInterval後的onTick()時刻。


Android中的倒計時實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.