我想做的是当计时器结束时,当还剩下 5 秒时,会发生一个动作

I want to make it so that when the timer ends, when there are still 5 seconds left, an action occurs

如何让这个动作发生在时间结束还剩5秒的时候。

这是我想在计时器还剩 5 秒时执行的操作的代码:

mTextViewCountDown.setTextColor(Color.RED);
    zooming_second = AnimationUtils.loadAnimation(Level1.this, R.anim.watch_zoo);
    mTextViewCountDown.startAnimation(zooming_second);
    soundPlay(watch);

在这个方法中:

//variable start
    private static final long START_TIME_IN_MILLIS = 60000;
    private TextView mTextViewCountDown;
    private CountDownTimer mCountDownTimer;
    private boolean mTimerRunning;
    private long mTimeLeftInMillis = START_TIME_IN_MILLIS;
//variable end

private void startTimer() {
        mCountDownTimer = new CountDownTimer(mTimeLeftInMillis, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                mTimeLeftInMillis = millisUntilFinished;

                int minutes = (int) (mTimeLeftInMillis / 1000) / 60;
                int seconds = (int) (mTimeLeftInMillis / 1000) % 60;

                String timeLeftFormatted = String.format(Locale.ENGLISH, "%02d:%02d", minutes, seconds);
                mTextViewCountDown.setText(timeLeftFormatted);

                mTimerRunning = true;
            }

            @Override
            public void onFinish() {
                mTimerRunning = false;
                TimeOutDialog();
                soundPlay(time_out_sound);
                mediaPlayer1.stop();
                tadam_false.stop();
                tadam_true.stop();
            }
        }.start();
    }

    private void pauseTimer () {
        mCountDownTimer.cancel();
        mTimerRunning = false;
    }

onTick(long) 方法中只需检查还剩多少秒。如果是五,触发你的行动。

编辑
我在正确的时间点的方法是这样的:

if (Math.abs(mTimeLeftInMillis - 5000) < 100) {
    // start the animation
}

这将避免 if (mTimeLeftInMillis == 5000) 出现问题,因为它给了它一些缓冲。它是必需的,因为它不会恰好在 5000 毫秒时触发。

谢谢!我是这样做的:


                 if (mTimeLeftInMillis <= 6000){
                   mTextViewCountDown.setTextColor(Color.RED);
                   zooming_second = AnimationUtils.loadAnimation(Level1.this, 
               R.anim.watch_zoo);
                   mTextViewCountDown.startAnimation(zooming_second);
                   soundPlay(watch);
               }