Notify PushServiceManager about PushService's started state

This commit is contained in:
cketti 2024-04-25 16:35:42 +02:00
parent 6bc1633897
commit ce1ea7324f
2 changed files with 27 additions and 1 deletions

View file

@ -13,6 +13,7 @@ import timber.log.Timber
* Foreground service that is used to keep the app alive while listening for new emails (Push).
*/
class PushService : Service() {
private val pushServiceManager: PushServiceManager by inject()
private val pushNotificationManager: PushNotificationManager by inject()
private val pushController: PushController by inject()
@ -22,10 +23,12 @@ class PushService : Service() {
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Timber.v("PushService.onStartCommand()")
Timber.v("PushService.onStartCommand(%s)", intent)
super.onStartCommand(intent, flags, startId)
startForeground()
notifyServiceStarted()
initializePushController()
return START_STICKY
@ -34,6 +37,7 @@ class PushService : Service() {
override fun onDestroy() {
Timber.v("PushService.onDestroy()")
pushNotificationManager.setForegroundServiceStopped()
notifyServiceStopped()
super.onDestroy()
}
@ -48,6 +52,18 @@ class PushService : Service() {
}
}
private fun notifyServiceStarted() {
// If our process was low-memory killed and now this service is being restarted by the system,
// PushServiceManager doesn't necessarily know about this service's state. So we're updating it now.
pushServiceManager.setServiceStarted()
}
private fun notifyServiceStopped() {
// Usually this service is only stopped via PushServiceManager. But we still notify PushServiceManager here in
// case the system decided to stop the service (without killing the process).
pushServiceManager.setServiceStopped()
}
private fun initializePushController() {
// When the app is killed by the system and later recreated to start this service nobody else is initializing
// PushController. So we'll have to do it here.

View file

@ -30,6 +30,16 @@ internal class PushServiceManager(private val context: Context) {
}
}
fun setServiceStarted() {
Timber.v("PushServiceManager.setServiceStarted()")
isServiceStarted.set(true)
}
fun setServiceStopped() {
Timber.v("PushServiceManager.setServiceStopped()")
isServiceStarted.set(false)
}
private fun startService() {
try {
val intent = Intent(context, PushService::class.java)