显示handler的剩余时间

Display the remaining time of the handler

我想知道如何在我的处理程序中显示剩余时间。 当我单击一个按钮时,我 运行 我的处理程序 x 秒,我想在处理程序结束之前在屏幕上显示倒计时。

试试这个:

    int time = 60;  // seconds
    final Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        public void run() {
            time--;
            mTextView.setText(time + " seconds");
        }
    };
    handler.postDelayed(runnable, 1000);

official documentation

Example of showing a 30 second countdown in a text field:

new CountDownTimer(30000, 1000) {
     public void onTick(long millisUntilFinished) {
         mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
     }

     public void onFinish() {
         mTextField.setText("done!");
     }
}.start();

It works fine thank you, last detail, if I put 5 seconds, it shows: 5, 4, 3, 2, 1 and 0. In the end it's 6 seconds.

Maxime,正如我在您对 Thomas Mary 的回答的评论中所读到的,您希望避免额外调用 onTick()。

你看到这个是因为 CountDownTimer 的 original implementation 在计时器启动后(没有延迟)第一次调用 onTick()。

How to remove the 0 at the end?

为此,您可以使用经过修改的 CountDownTimer:

public abstract class CountDownTimer {

private final long mMillisInFuture;
private final long mCountdownInterval;
private long mStopTimeInFuture;

private boolean mCancelled = false;

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

public synchronized final void cancel() {
    mCancelled = true;
    mHandler.removeMessages(MSG);
}

public synchronized final CountDownTimer start() {
    mCancelled = false;
    if (mMillisInFuture <= 0) {
        onFinish();
        return this;
    }
    mStopTimeInFuture = SystemClock.elapsedRealtime() + mMillisInFuture;
    onTick(mMillisInFuture);
    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG), mCountdownInterval);
    return this;
}

public abstract void onTick(long millisUntilFinished);

public abstract void onFinish();

private static final int MSG = 1;

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 {
                onTick(millisLeft);
                sendMessageDelayed(obtainMessage(MSG), mCountdownInterval);
            }
        }
    }
};
}

请注意,您可能需要相应地调整 onTick() 方法中的实现。