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

时间:2017-11-16 03:18:45

标签: 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 个答案:

答案 0 :(得分:2)

你可以试试这个。

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