I have a CountDownTimer that runs in a service when the app is in the background, onFinish(), the timer is supposed to check whether to start another timer or send a notification, the trouble is that once the timer is finished and the second timer is called, onDestroy is called at the same instant.
onStartCommand
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
startTimer()
return START_STICKY
}
startTimer
private fun startTimer() {
val context = this
Timber.tag(TAG).d("startTimer: called with time left " + timeLeftInMillis / 1000)
Timber.tag(TAG).d("startTimer: called timerType is " + timerType)
// get values from datastore
timer = object : CountDownTimer(timeLeftInMillis, 1000) {
override fun onTick(millisUntilFinished: Long) {
timeLeftInMillis = millisUntilFinished
// Update notification text with remaining time
notificationBuilder.setContentText("Time remaining: ${millisUntilFinished / 1000} seconds")
notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build())
}
override fun onFinish() {
timerState = TimerState.STOPPED
if (timerType == TimerType.LONGBREAK || timerType == TimerType.SHORTBREAK) {
//save timer values to dataStore
scope.launch {
currentPom++
timerType = TimerType.FOCUS
timerState = TimerState.STOPPED
dataStoreManager.saveRunningParams(
timeLeftInMillis,
timerType.ordinal,
timerState.ordinal,
appVisibility.ordinal,
currentPom
)
//send notification
showTimerCompleteNotification(context)
}
} else if (timerType == TimerType.FOCUS) {
//start next timer
nextTimer()
loadPomValues()
startTimer()
}
}
}
timer.start()
}
log messages
2024-01-06 10:25:17.631 15069-15069 TimerService com.example.taskrabbit D TimerService nextTimer: Called
2024-01-06 10:25:17.632 15069-15069 TimerService com.example.taskrabbit D TimerService nextTimer: current timer type is SHORTBREAK
2024-01-06 10:25:17.632 15069-15069 TimerService com.example.taskrabbit D startTimer: called with time left 60
2024-01-06 10:25:17.633 15069-15069 TimerService com.example.taskrabbit D startTimer: called timerType is SHORTBREAK
2024-01-06 10:25:17.634 15069-15069 TimerService com.example.taskrabbit D onDestroy: called
2024-01-06 10:25:17.636 15069-15099 TimerService com.example.taskrabbit D onDestroy: Time left in millis is: 60
What prevents the server not to close immediately? It should close already after the first startTimer() call as far as i can see.
server==service