AndroidStudio(WearOS)로 Interval Timer 만들기 : PAUSE 후 RESTART 시 타이머 초기화 버그 해결

LeeYulhee·2024년 4월 15일

👉 문제 원인 및 해결 방안


  • PAUSE를 누르고 RESTART를 누르면 남은 시간에서 시작하는 게 아니라 해당 SET를 새로 시작
  • 현재 SET와 남은 SET는 문제 없이 유지되었음



👉 기존 코드


private void startTimer() {
    currentSet = executionSet;
    setupAndStartTimer();
}

private void restartTimer() {
    if (isPaused && currentSet > 0) {
        isPaused = false;
        setupAndStartTimer();
        updatePauseButtonText();
    }
}

private void setupAndStartTimer() {
    timeLeftInMillis = intervalTime * 1000L; // 남은 시간을 설정
    countDownTimer = new CountDownTimer(timeLeftInMillis, 100) {
        @Override
        public void onTick(long millisUntilFinished) {
            timeLeftInMillis = millisUntilFinished;
            updateTimerText(millisUntilFinished);
        }
        @Override
        public void onFinish() {
            if (currentSet > 1) {
                notifyInterval();
                currentSet--;
                setupAndStartTimer(); // 다시 타이머 시작
            } else {
                notifyCompletion();
            }
        }
    }.start();
}


👉 문제 원인 및 해결 방안


  • restartTimer 메서드를 호출할 때, setupAndStartTimer 메서드가 호출됨
  • setupAndStartTimer 메서드에서 남은 시간(timeLeftInMillis)에 intervalTime * 1000을 새로 대입
  • 위 과정 때문에 timeLeftInMillis 남은 시간이 대입되어 있지 않고 계속 새로 시간을 시작
  • ⇒ timeLeftInMillis에 intervalTime * 1000을 대입하는 시점 변경



👉 수정한 코드


private void startTimer() {
    timeLeftInMillis = intervalTime * 1000L;
    setupAndStartTimer();
}

private void restartTimer() {
    if (isPaused) {
        isPaused = false;
        setupAndStartTimer();
        updatePauseButtonText();
    }
}

private void setupAndStartTimer() {
    timeLeftInMillis = intervalTime * 1000L; // 남은 시간
    countDownTimer = new CountDownTimer(timeLeftInMillis, 100) {
        @Override
        public void onTick(long millisUntilFinished) {
            timeLeftInMillis = millisUntilFinished;
            updateTimerText(millisUntilFinished);
        }
        @Override
        public void onFinish() {
            if (currentSet > 1) {
                notifyInterval();
                currentSet--;
                startTimer(); // 다시 타이머 시작
            } else {
                notifyCompletion();
            }
        }
    }.start();
}
profile
끝없이 성장하고자 하는 백엔드 개발자입니다.

0개의 댓글