java - 计算处理程序中的剩余时间

标签 java android timer handler

我有一个等待“syncingIntervalsInt”时间然后执行代码的函数。如何创建倒计时?例如,当syncingIntervalsInt设置为10秒时,我想将一个TextView设置为倒计时10、9、8等。

这是我的功能:

public void refreshRecycler()
{
    countingTillSync = syncingIntervalsInt;

    timerHandler = new Handler();

    timerRunnable = new Runnable() {


        @Override
        public void run() {

           //some code here
           countingTillSync--;


        }

        timerHandler.postDelayed(this, syncingIntervalsInt*1000); //run every second
    }


    timerHandler.postDelayed(timerRunnable, syncingIntervalsInt*1000); //Start timer after 1 sec

}

上面的代码仅在syncingIntervalsInt*1000时间后递减,这不是我所期望的。

最佳答案

你可以试试这个。

1.添加CountDownTimerUtils

public class CountDownTimerUtils extends CountDownTimer {

private TextView mTextView;

/**
 * @param textView          The TextView
 * @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 receiver
 *                          {@link #onTick(long)} callbacks.
 */
public CountDownTimerUtils(TextView textView, long millisInFuture, long countDownInterval) {
    super(millisInFuture, countDownInterval);
    this.mTextView = textView;
}
@Override
public void onTick(long millisUntilFinished) {
    mTextView.setText(millisUntilFinished / 1000 + "sec");
    mTextView.setClickable(false);
}
@Override
public void onFinish() {
    mTextView.setText("retry");
    mTextView.setClickable(true);
    mTextView.setFocusable(true);
}
}

2.像这样在代码中设置。

// 1 param yourTextView was TextView you want to set 
// 2 param  10 * 1000 was the number of millis in the future from the call
// 3 param 1000 was the interval along the way to receiver
CountDownTimerUtils mTimerUtils = new CountDownTimerUtils(yourTextView, 10 * 1000, 1000);
mTimerUtils.start();

关于java - 计算处理程序中的剩余时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47321001/

相关文章:

android - 将依赖项包含在 Android 库中的最佳方式?

java - 如何在 Eclipse 控制台 (Java) 中记录循环

ios - slider 擦洗不太顺畅

java - 无法启动 Swing 计时器

javascript - 连续调用 XMLHttpRequest

java - JInternalFrame 和键绑定(bind)

java - JPA 2 Criteria 与抽象集合相结合

java - 来自 HTTP 的 XML 解析文件

java - 在 AbstractJdbcUsernamePasswordAuthenticationHandler 中获取 Request 对象

android - Codepush React Native Android staging- 在根项目中找不到任务 installReleaseStagingDebug