如何通过计时器类循环延迟时间?

时间:2018-11-10 10:47:07

标签: java android for-loop countdowntimer

我希望运行计时器大约30000 ms,每次最多运行8次或更多,所以这是我的循环,但它在30000ms之后立即运行所有计时器

    public void repeatTimerTask() {
    repeat = 8; // need to run 30 sec timer for 8 times but one after one

    startTimer(30000); // firsat timer for 30 sec

    Handler handler = new Handler();
    for (int a = 1; a<=repeat; a++) {

        final int finalA = a;
        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                startTimer(30000);

            }

        }, 30000); // delay until to finish first timer for 30 sec
    }
}

2 个答案:

答案 0 :(得分:0)

要运行n秒钟的计时器,您可以使用CountDownTimer

声明两个自变量。一个要重复的次数。还有一个可以保持计数。

 private int NUM_REPEAT = 4;
 private int REPEAT_COUNT = 0;

然后在任何需要的地方调用此方法。需要注意的一件事是,如果要运行5次此循环,则必须给出重复次数4。导致对该函数进行饱和处理,因此必须对其进行调用,以免计数。

private void startTimer() {

    new CountDownTimer(3000, 1000) {
        int secondsLeft = 0;

        public void onTick(long ms) {
            if (Math.round((float) ms / 1000.0f) != secondsLeft) {
                secondsLeft = Math.round((float) ms / 1000.0f);
                // resend_timer is a textview
                 resend_timer.setText("remaining time is "+secondsLeft);
                ;
            }
        }

        public void onFinish() {
            Log.d(TAG, "timer finished "+REPEAT_COUNT);
            if (REPEAT_COUNT <= NUM_REPEAT) {
                startTimer();
                REPEAT_COUNT++;
            }

        }
    }.start();
}

答案 1 :(得分:0)

请尝试以下代码,并在您首先要启动计时器的位置调用“ startTimer”方法:

private int startTimerCount = 1, repeat = 8;

private void startTimer(){
    // if startTimerCount is less than 8 than the handle will be created
    if(startTimerCount <= repeat){
        // this will create a handler which invokes startTimer method after 30 seconds
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                startTimer();
            }
        }, 30000);

        // do what you want
        Toast.makeText(this, "startTimer " + startTimerCount, Toast.LENGTH_SHORT).show();
    }
    startTimerCount++;
}