Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發實例 >> Android 定時器

Android 定時器

編輯:Android開發實例

對於一個Java開發者來說,想到定時器(計時器,倒計時)的應用 一般都會想到使用 java.util.Timer 和 java.util.TimerTask , 在Android中使用這2個類也可以實現計時的功能 但是使用起來還是有點麻煩的, 特別是在UI界面需要更新的時候, 例如 實現一個倒計時的界面, 在一個TextView中顯示當前剩余的時間, 如果在TimerTask中計時,則無法更新TextView顯示的剩余時間(在非UI線程中 不能訪問UI組件),可以通過runOnUiThread函數來實現 但是多少有點煩瑣

在Android 實現定時比較推薦的方式還是使用 android.os.Handler 中的 postXXX 和sendXXX 等方法. 細心的開發者可能已經注意到Android提供了一個倒計時的助手類 android.os.CountDownTimer 來方便實現倒計時的功能. 她就是通過handler的 sendMessageDelayed 來實現的. 使用該類來顯示一個倒計時的TextView是很方便的:
 

 	TextView mTv;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		mTv = (TextView) findViewById(R.id.tv);
		mTv.setText("test");
		new CountDownTimer(30000,100) {

			@Override
			public void onTick(long millisUntilFinished) {
				mTv.setText("seconds remaining: " +
					millisUntilFinished / 1000+" S "+(millisUntilFinished % 1000)/100);
			}

			@Override
			public void onFinish() {
				mTv.setText("Done!");
			}
		}.start();

CountDownTimer的源代碼如下

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;

    /**
     * @param millisInFuture The number of millis in the future from the call
     *   to [email protected] #start()} until the countdown is done and [email protected] #onFinish()}
     *   is called.
     * @param countDownInterval The interval along the way to receive
     *   [email protected] #onTick(long)} callbacks.
     */
    public CountDownTimer(long millisInFuture, long countDownInterval) {
        mMillisInFuture = millisInFuture;
        mCountdownInterval = countDownInterval;
    }

    /**
     * Cancel the countdown.
     */
    public final void cancel() {
        mHandler.removeMessages(MSG);
    }

    /**
     * Start the countdown.
     */
    public synchronized final CountDownTimer start() {
        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) {
                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);
                }
            }
        }
    };
}
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved