использовать для цикла в таймер андроид студии - PullRequest
0 голосов
/ 28 мая 2018

Я пытаюсь создать таймер, который будет запускаться x раз за определенную продолжительность.Пример: 10 - количество секунд, которое таймер должен запустить.3 - это количество раз, которое должен завершиться 10-секундный таймер.

В идеале он должен начать отсчет 10 секунд (или любое другое переменное время) в первый раз.Тогда играйте звук.Затем начните обратный отсчет снова (второй раз).Тогда играйте звук.Затем начните обратный отсчет снова (в третий раз).Затем воспроизведите звук и прекратите выполнение и сделайте что-нибудь еще.

До сих пор я создал цикл for, который вызывает метод таймера, но кажется, что он работает только 1x.Кто-нибудь может увидеть, что я делаю не так?

    private void startRound(){
    for ( int i = 0; i < mRounds; i++){
        startTimer();
    }
}

private void startTimer(){
        CountDownTimer = new CountDownTimer(mTimeLeft, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                mTimeLeft = millisUntilFinished;
                updateCountDownText();
            }

            @Override
            public void onFinish() {
                textView.setText("FINISHED");
                mTimerRunning = false;
                mButtonStartPause.setText("START");
                mButtonStartPause.setVisibility(View.INVISIBLE);
                ;
                mButtonReset.setVisibility(View.VISIBLE);
            }
        }.start();
        mTimerRunning = true;
        mButtonStartPause.setText("Pause");
        mButtonReset.setVisibility(View.INVISIBLE);
}

1 Ответ

0 голосов
/ 28 мая 2018

Это потому, что цикл for не ожидает завершения CountDownTimer .И запустит 3 таймера обратного отсчета ~ мгновенно.Для повторения простых периодических задач обработчик рекомендуется в Android.См. Эту ссылку .

. Класс CountDownTimer в Android сам использует внутренний обработчик.

Вы можете создать обработчик и передать ему работоспособный объект.Примерно так:

        int numberOfTimers = 3;
        int numberOfSeconds = 10;

        Handler timerHandler = new Handler();

    /**
     * Inner class that implements {@link Runnable} to check the timer updates.
     */
    class RunnableTimer implements Runnable {
        int numberOfSeconds;
        int secRemaining;
        int timesRemaining;

        RunnableTimer(int numberOfSeconds, int timesRemaining) {
            this.numberOfSeconds = numberOfSeconds;
            this.timesRemaining = timesRemaining;
            secRemaining = numberOfSeconds;
        }

        @Override
        public void run() {
            if(secRemaining>0){
                    --secRemaining; // decrease the remaining seconds by 1.
                    updateText() // upadate the textView with remaining seconds.
                    handler.postDelayed(this,1000); // repeat the runnable after 1 sec
                }else {
                    timesRemaining--; // decrease the number of timer by 1 when countdown finishes
                    updateTextWhenTimerFinished() // update the text when the countdown finishes
                    playSound(); // play the sound

                    // check if the timer has to run more times
                    if( timesRemaining > 0 ){
                        secRemaining = numberOfSeconds; // re-initialize the timer seconds
                        handler.postDelayed(this,1000); // repeat the runnable after 1 sec
                    }   
                }
        }

        RunnableTimer timerRunnable = new RunnableTimer(numberOfSeconds, numberOfTimers);

       //finally pass the runnable in the handler to start the timer
       timerHandler.post(timerRunnable);

Не забудьте вызвать timerHandler.removeCallbacks (timerRunnable) в onStop () вашей активности.

...