可以動態修改時間的CountDownTimer

在做一個功能的時候,用到了CountDownTimer,做爲一個倒計時功能類,用起來挺方便的。然而,我想動態修改倒計時時間,發現竟然沒有這個接口!

經過一陣鼓搗,發現可以有兩種方案來實現。

1,通過反射;
2,重寫CountDownTimer,添加上修改倒計時時間的接口。

下面分別描述:

1,通過反射,動態修改倒計時時間

我們知道,在CountDownTimer的構造函數中有兩個參數,如下:

public CountDownTimer(long millisInFuture, long countDownInterval)

通過查看源碼,可以知道,這兩個參數,是這樣使用的:

    public CountDownTimer(long millisInFuture, long countDownInterval) {
        mMillisInFuture = millisInFuture;
        mCountdownInterval = countDownInterval;
    }

很顯然,接收參數的,就是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;

描述也很簡潔,mMillisInFuture是從啓動到停止的毫秒數,也就是執行完成的總時間間隔,執行完成後會調用onFinish方法;
mCountdownInterval是用戶接收回調的間隔時間,單位也是毫秒,執行的回調方法是onTick。
找到它們了,剩下的事情就是反射了。
我做了兩個函數,來分別設置這兩個參數:

//利用反射動態地改變CountDownTimer類的私有字段mCountdownInterval
    private void changeCountdownInterval(long time) {
        try {
            // 反射父類CountDownTimer的mCountdownInterval字段,動態改變回調頻率
            Class clazz = Class.forName("android.os.CountDownTimer");
            Field field = clazz.getDeclaredField("mCountdownInterval");
            //從Toast對象中獲得mTN變量
            field.setAccessible(true);
            field.set(timethis, time);          
        } catch (Exception e) {
            Log.e("Ye", "反射類android.os.CountDownTimer.mCountdownInterval失敗:" + e);
        }
    }

//利用反射動態地改變CountDownTimer類的私有字段mMillisInFuture
    private void changeMillisInFuture(long time) {
        try {
            // 反射父類CountDownTimer的mMillisInFuture字段,動態改變定時總時間
            Class clazz = Class.forName("android.os.CountDownTimer");
            Field field = clazz.getDeclaredField("mMillisInFuture");
            field.setAccessible(true);
            field.set(timethis, time);
        } catch (Exception e) {
            Log.e("Ye", "反射類android.os.CountDownTimer.mMillisInFuture失敗: "+ e);
        }
    }

說明下,這裏的timethis,是一個CountDownTimer對象,

timethis = new CountDownTimer(365*24*3600 * 1000, 1000){...};

我這樣定義,是避免定時器很快到時間了,導致異常,所以初始值定義到了一年這麼長。其實,定義一個小間隔也沒有問題,因爲我們還沒有啓動定時器。

下面,就可以調用修改定時長度的函數了。

changeCountdownInterval(500);   
changeMillisInFuture(timeOutSeconds * 1000);    
timethis.start();   

2,重寫CountDownTimer,添加上修改倒計時時間的接口

代碼如下:

package cn.timer;

import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;


/* The calls to {@link #onTick(long)} are synchronized to this object so that
        * one call to {@link #onTick(long)} won't ever occur before the previous
        * callback is complete.  This is only relevant when the implementation of
        * {@link #onTick(long)} takes an amount of time to execute that is significant
        * compared to the countdown interval.
        */

public abstract class CountDownTimerUtil {

    /**
     * Millis since epoch when alarm should stop.
     */
    private long mMillisInFuture;

    /**
     * The interval in millis that the user receives callbacks
     */
    private long mCountdownInterval;

    private long mStopTimeInFuture;

    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 CountDownTimerUtil(long millisInFuture, long countDownInterval) {
        mMillisInFuture = millisInFuture;
        mCountdownInterval = countDownInterval;
    }


    public final void setCountdownInterval(long countdownInterval) {
        mCountdownInterval = countdownInterval;
    }

    public final void setMillisInFuture(long millisInFuture) {
        mMillisInFuture = millisInFuture;       
    }

    /**
     * Cancel the countdown.
     *
     * Do not call it from inside CountDownTimer threads
     */
    public final void cancel() {
        mHandler.removeMessages(MSG);
        mCancelled = true;
    }

    /**
     * Start the countdown.
     */
    public synchronized final CountDownTimerUtil start() {
        if (mMillisInFuture <= 0) {
            onFinish();
            return this;
        }
        mStopTimeInFuture = SystemClock.elapsedRealtime() + mMillisInFuture;
        mHandler.sendMessage(mHandler.obtainMessage(MSG));
        mCancelled = false;
        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 (CountDownTimerUtil.this) {
                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;

                    if (!mCancelled) {
                        sendMessageDelayed(obtainMessage(MSG), delay);
                    }
                }
            }
        }
    };
}

調用代碼如下:

創建實例:

timethis = new CountDownTimerUtil(365*24*3600 * 1000, 1000){...};

在需要的時刻,進行動態修改:

    timethis.setCountdownInterval(500);
    timethis.setMillisInFuture(timeOutSeconds * 1000);
    timethis.start();   

如果是創建後就修改,這樣順序的執行,其實也沒有什麼特殊的效果。能顯示動態修改價值的地方,是在某種時刻執行,例如,在按鈕點擊時執行,動態修改就很有必要了。

參考文章:
http://www.cnblogs.com/yexiubiao/archive/2013/01/02/2842026.html
http://blog.csdn.net/liuweiballack/article/details/46605787

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章