9

根据我的观察,滴答之间的 android CountDownTimer countDownInterval 恰好不准确,countDownInterval 通常比指定的长几毫秒。我的特定应用程序中的 countDownInterval 是 1000 毫秒,只是以一秒的步长倒计时一定的时间。

由于这个延长的滴答声,当倒计时计时器运行足够长的时间时,我最终得到的滴答声比想要的要少,这会破坏显示的时间倒计时(当累积足够多的额外毫秒时,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 正忙于后台进程或不同的线程,那么它在完成之前不会调用计时器。

您可能会更幸运地将间隔更改为更小的值,例如 100 毫秒,然后仅在发生更改时才重新绘制屏幕。使用这种方法,计时器不会直接导致任何事情发生,它只是定期重绘屏幕。

于 2012-10-06T17:54:29.460 回答
0

我知道它很旧,但它是你永远需要的东西。我编写了一个名为 TimedTaskExecutor 的类,因为我需要每隔 x 毫秒运行一个特定命令,持续时间未知。我的首要任务之一是使 x 尽可能准确。我尝试使用 AsyncTask、Handlers 和 CountdownTimer,但都给了我不好的结果。这是课程:

package com.example.myapp;

import java.util.concurrent.TimeUnit;

/*
 * MUST RUN IN BACKGROUND THREAD
 */
public class TimedTaskExecutor {
// ------------------------------ FIELDS ------------------------------

/**
 *
 */
private double intervalInMilliseconds;

/**
 *
 */
private IVoidEmptyCallback callback;

/**
 *
 */
private long sleepInterval;

// --------------------------- CONSTRUCTORS ---------------------------

/**
 * @param intervalInMilliseconds
 * @param callback
 */
public TimedTaskExecutor(double intervalInMilliseconds, IVoidEmptyCallback callback, long sleepInterval) {
    this.intervalInMilliseconds = intervalInMilliseconds;
    this.callback = callback;
    this.sleepInterval = sleepInterval;
}

// --------------------- GETTER / SETTER METHODS ---------------------

/**
 * @return
 */
private IVoidEmptyCallback getCallback() {
    return callback;
}

/**
 * @return
 */
private double getIntervalInMilliseconds() {
    return intervalInMilliseconds;
}

/**
 * @return
 */
private long getSleepInterval() {
    return sleepInterval;
}

// -------------------------- OTHER METHODS --------------------------

/**
 *
 */
public void run(ICallback<Boolean> isRunningChecker) {

    long nanosInterval = (long) (getIntervalInMilliseconds() * 1000000);

    Long previousNanos = null;

    while (isRunningChecker.callback()) {

        long nanos = TimeUnit.NANOSECONDS.toNanos(System.nanoTime());

        if (previousNanos == null || (double) (nanos - previousNanos) >= nanosInterval) {

            getCallback().callback();

            if (previousNanos != null) {

                // Removing the difference
                previousNanos = nanos - (nanos - previousNanos - nanosInterval);

            } else {

                previousNanos = nanos;

            }

        }

        if (getSleepInterval() > 0) {

            try {

                Thread.sleep(getSleepInterval());

            } catch (InterruptedException ignore) {
            }

        }

    }

}

// -------------------------- INNER CLASSES --------------------------

/**
 *
 */
public interface IVoidEmptyCallback {
    /**
     *
     */
    public void callback();
}

/**
 * @param <T>
 */
public interface ICallback<T> {
    /**
     * @return
     */
    public T callback();
}

}

以下是如何使用它的示例:

private boolean running;

Handler handler = new Handler();

handler.postDelayed(
    new Runnable() {
        /**
         *
         */
        @Override
        public void run() {
            running = false;
        }
    },
    5000
);

HandlerThread handlerThread = new HandlerThread("For background");
handlerThread.start();

Handler background = new Handler(handlerThread.getLooper());

background.post(
    new Runnable() {
        /**
         *
         */
        @Override
        public void run() {

            new TimedTaskExecutor(
                    10, // Run tick every 10 milliseconds
                    // The callback for each tick
                    new TimedTaskExecutor.IVoidEmptyCallback() {
                        /**
                         *
                         */
                        private int counter = 1;

                        /**
                         *
                         */
                        @Override
                        public void callback() {
                            // You can use the handler to post runnables to the UI
                            Log.d("runTimedTask", String.valueOf(counter++));
                        }
                    },
                    // sleep interval in order to allow the CPU to rest
                    2
            ).run(
                    // A callback to check when to stop
                    new TimedTaskExecutor.ICallback<Boolean>() {
                        /**
                         *
                         * @return
                         */
                        @Override
                        public Boolean callback() {
                            return running;
                        }
                    }
            );

        }
    }
 );

运行此代码将产生 500 次或多或少准确 x 的调用。(降低睡眠因子使其更准确)

  • 编辑:似乎在带有 Lollipop 的 Nexus 5 中,您应该在睡眠因子中使用 0。
于 2014-11-27T06:37:57.037 回答
0

正如 Nathan Villaescusa 之前所写,好的方法是减少“滴答”间隔,然后通过检查这是否实际上是新的秒来每秒触发所需的 ACTIONS。

伙计们,看看这种方法:

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

我写了一个库来防止这种现象。
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 回答