如何通过定时器 class 循环延迟时间?

How to loop through timer class for delayed time?

我想要 运行 计时器大约 30000 毫秒,每次最多 8 次或更多次,所以这是我的循环,但它 运行 在 30000 毫秒后立即所有计时器

    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
    }
}

要运行一个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();
}

请尝试下面的代码,并在您首先要启动计时器的地方调用 '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++;
}