9

私の観察から、ティック間のアンドロイド CountDownTimer countDownInterval はたまたま正確ではありません.countDownIntervalは、指定されたよりも数ミリ秒長くなります。私の特定のアプリの countDownInterval は 1000 ミリ秒で、1 秒単位で一定の時間をカウントダウンするだけです。

この長いティックのために、カウントダウンタイマーが十分に長く実行され、表示された時間のカウントダウンが台無しになると、ティックが少なくなってしまいます(十分な追加のミリ秒が合計されると、UIレベルで2秒のステップが発生します)

CountDownTimer のソースを調べると、この望ましくない不正確さを修正できるようにねじることができるようですが、Java/Android の世界で利用可能なより優れた CountDownTimer が既にあるかどうか疑問に思っていました。

ポインタをくれた仲間に感謝します...

4

6 に答える 6

18

リライト

あなたが言ったように、次onTick()の時間は前回の実行時間から計算されることにも気付きました。これにより、ティックごとonTick()に小さなエラーが発生します。CountDownTimer のソース コードを、開始時刻から指定された間隔でそれぞれ呼び出すように変更しました。onTick()

私はこれを CountDownTimer フレームワークに基づいて構築しているので、ソース コードをカット アンド ペーストしてプロジェクトに貼り付け、クラスに一意の名前を付けます。(私は MoreAccurateTimer と呼んでいます。) 次に、いくつかの変更を行います。

  1. 新しいクラス変数を追加します。

    private long mNextTime;
    
  2. 変更start():

    public synchronized final MoreAccurateTimer start() {
        if (mMillisInFuture <= 0) {
            onFinish();
            return this;
        }
    
        mNextTime = SystemClock.uptimeMillis();
        mStopTimeInFuture = mNextTime + mMillisInFuture;
    
        mNextTime += mCountdownInterval;
        mHandler.sendMessageAtTime(mHandler.obtainMessage(MSG), mNextTime);
        return this;
    }
    
  3. ハンドラーの変更handlerMessage():

    @Override
    public void handleMessage(Message msg) {
        synchronized (MoreAccurateTimer.this) {
            final long millisLeft = mStopTimeInFuture - SystemClock.uptimeMillis();
    
            if (millisLeft <= 0) {
                onFinish();
            } else {
                onTick(millisLeft);
    
                // Calculate next tick by adding the countdown interval from the original start time
                // If user's onTick() took too long, skip the intervals that were already missed
                long currentTime = SystemClock.uptimeMillis();
                do {
                    mNextTime += mCountdownInterval;
                } while (currentTime > mNextTime);
    
                // Make sure this interval doesn't exceed the stop time
                if(mNextTime < mStopTimeInFuture)
                    sendMessageAtTime(obtainMessage(MSG), mNextTime);
                else
                    sendMessageAtTime(obtainMessage(MSG), mStopTimeInFuture);
            }
        }
    }
    
于 2012-10-06T18:06:28.950 に答える
4

これが私が思いついたものです。これは、元の CountDownTimer を少し変更したものです。追加されるのは、呼び出されたティックの量をカウントする変数 mTickCounter です。この変数は、新しい変数 mStartTime と一緒に使用して、ティックの精度を確認します。この入力に基づいて、次のティックまでの遅延が調整されます...私が探していたものを実行しているようですが、これは改善できると確信しています。

探す

// ************AccurateCountdownTimer***************

ソースコードで、元のクラスに追加した変更を見つけます。

package com.dorjeduck.xyz;

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

/**
 * Schedule a countdown until a time in the future, with regular notifications
 * on intervals along the way.
 * 
 * Example of showing a 30 second countdown in a text field:
 * 
 * <pre class="prettyprint">
 * new CountDownTimer(30000, 1000) {
 * 
 *  public void onTick(long millisUntilFinished) {
 *      mTextField.setText(&quot;seconds remaining: &quot; + millisUntilFinished / 1000);
 *  }
 * 
 *  public void onFinish() {
 *      mTextField.setText(&quot;done!&quot;);
 *  }
 * }.start();
 * </pre>
 * 
 * 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 AccurateCountDownTimer {

    /**
     * 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;

    // ************AccurateCountdownTimer***************
    private int mTickCounter;
    private long mStartTime;

    // ************AccurateCountdownTimer***************

    /**
     * @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 AccurateCountDownTimer(long millisInFuture, long countDownInterval) {
        mMillisInFuture = millisInFuture;
        mCountdownInterval = countDownInterval;

        // ************AccurateCountdownTimer***************
        mTickCounter = 0;
        // ************AccurateCountdownTimer***************
    }

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

    /**
     * Start the countdown.
     */
    public synchronized final AccurateCountDownTimer start() {
        if (mMillisInFuture <= 0) {
            onFinish();
            return this;
        }

        // ************AccurateCountdownTimer***************
        mStartTime = SystemClock.elapsedRealtime();
        mStopTimeInFuture = mStartTime + mMillisInFuture;
        // ************AccurateCountdownTimer***************

        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 (AccurateCountDownTimer.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);

                    // ************AccurateCountdownTimer***************
                    long now = SystemClock.elapsedRealtime();
                    long extraDelay = now - mStartTime - mTickCounter
                            * mCountdownInterval;
                    mTickCounter++;
                    long delay = lastTickStart + mCountdownInterval - now
                            - extraDelay;

                    // ************AccurateCountdownTimer***************

                    // take into account user's onTick taking time to execute

                    // special case: user's onTick took more than interval to
                    // complete, skip to next interval
                    while (delay < 0)
                        delay += mCountdownInterval;

                    sendMessageDelayed(obtainMessage(MSG), delay);
                }
            }
        }
    };
}
于 2012-10-06T19:35:06.557 に答える
2

ほとんどのシステムでは、タイマーが完全に正確であることはありません。システムは、他に何もすることがない場合にのみタイマーを実行します。CPU がバックグラウンド プロセスまたは別のスレッドでビジー状態の場合、終了するまでタイマーを呼び出すことはできません。

間隔を 100ms などの小さい値に変更し、何かが変更された場合にのみ画面を再描画する方が運が良いかもしれません。このアプローチでは、タイマーが直接何かを発生させるのではなく、定期的に画面を再描画するだけです。

于 2012-10-06T17:54:29.460 に答える
0

Nathan Villaescusa が以前に書いたように、「カチカチ音をたてる」間隔を短くしてから、これが実際に新しい秒であるかどうかを確認して、毎秒必要な ACTION を起動するのが良いアプローチです。

みんな、このアプローチを見てください:

new CountDownTimer(5000, 100) {

     int n = 5;
     Toast toast = null;

     @Override
     public void onTick(long l) {

         if(l < n*1000) {
             //
             // new seconds. YOUR ACTIONS
             //
             if(toast != null) toast.cancel();

             toast = Toast.makeText(MainActivity.this, "" + n, Toast.LENGTH_SHORT);
             toast.show();

             // this one is important!!!
             n-=1;
         }

     }

     @Override
     public void onFinish() {
         if(toast != null) toast.cancel();
         Toast.makeText(MainActivity.this, "START", Toast.LENGTH_SHORT).show();
     }
}.start();

これが誰かに役立つことを願っています;p

于 2019-08-18T14:07:14.353 に答える
-2

この現象を防ぐために、1 つの lib を作成しました。
https://github.com/imknown/NoDelayCountDownTimer

使用のためのコアコード:

private long howLongLeftInMilliSecond = NoDelayCountDownTimer.SIXTY_SECONDS;

private NoDelayCountDownTimer noDelayCountDownTimer;
private TextView noDelayCountDownTimerTv;

NoDelayCountDownTimer noDelayCountDownTimer = new NoDelayCountDownTimerInjector<TextView>(noDelayCountDownTimerTv, howLongLeftInMilliSecond).inject(new NoDelayCountDownTimerInjector.ICountDownTimerCallback() {
    @Override
    public void onTick(long howLongLeft, String howLongSecondLeftInStringFormat) {
        String result = getString(R.string.no_delay_count_down_timer, howLongSecondLeftInStringFormat);

        noDelayCountDownTimerTv.setText(result);
    }

    @Override
    public void onFinish() {
        noDelayCountDownTimerTv.setText(R.string.finishing_counting_down);
    }
});

メインベースロジックコード:

private Handler mHandler = new Handler(new Handler.Callback() {
    @Override
    public boolean handleMessage(Message msg) {

        synchronized (NoDelayCountDownTimer.this) {
            if (mCancelled) {
                return true;
            }

            final long millisLeft = mStopTimeInFuture - SystemClock.elapsedRealtime();

            if (millisLeft <= 0 || millisLeft < mCountdownInterval) {
                onFinish();
            } 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;
                }

                mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG), delay);
            }
        }

        return true;
    }
});

記録

于 2016-04-20T06:16:30.150 に答える