The Problem:
I am relatively new to Android development. A while ago I built a simple egg timer app which sounds an alarm once the timer reaches zero. I have noticed however, that if you use the app to set a timer several times in a row (start a new timer once the other one has finished), the alarm that is supposed to sound when the timer reaches zero is off by a random number of seconds.
As an example, I set a timer to run for two minutes, but the alarm never sounded until two minutes and thirty five seconds had passed. I then ran the same two minute test again, same result. I then set a timer for ten seconds, and the alarm never sounded until twenty six seconds had passed.
This behaviour appears to be completely random also. Sometimes the app works without issue, other times it behaves as described above.
What I have Tried:
I did notice that this issue only seems to appear once the app has gone into a background state. If the screen stays awake, the alarm will sound without issue, on time, every time.
I tried both connecting my physical device to Android Studio, and also using the simulator within Android Studio to try and debug the issue. The problem there is that it never appears to fail when connected to Android Studio. It just works every time.
My code for the CountDownTimer()
is as follows:
countDownTimer = new CountDownTimer(countdown * 1000, 1000) {
public void onTick(long timeTillEnd) {
timerView.setText(String.valueOf(DateUtils.formatElapsedTime(timeTillEnd / 1000)));
}
public void onFinish() {
final MediaPlayer mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.alarm_sound);
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(mp -> {
mediaPlayer.reset();
mediaPlayer.release();
});
resetCountdownTimer();
}
}.start();
The code that runs when the resetCountdownTimer()
function is called:
public void resetCountdownTimer() {
countDownTimer.cancel();
countdownIsActive = false;
togglePresets();
startStopButton.setText(R.string.start);
startStopButton.setActivated(false);
}
I also tried adding the user WAKE_LOCK
permissions to the AndroidManifest.xml
file and adding the following code to the onFinish()
function:
mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
Just before the mediaPlayer.start()
call to see if it would keep the MediaPlayer
awake, but I’m either using it wrong, misunderstanding the problem, or something else is happening because it never fixed the issue.
The app code is very small and simple. It all runs on the main thread. Using: compileSdkVersion 33, minSdkVersion 26, targetSdkVersion 33.
Can someone help me fix/understand this issue?