@@ -9,6 +9,9 @@ import android.os.IBinder
99import androidx.annotation.RequiresApi
1010import androidx.core.app.NotificationCompat
1111import androidx.core.content.ContextCompat
12+ import androidx.lifecycle.DefaultLifecycleObserver
13+ import androidx.lifecycle.LifecycleOwner
14+ import androidx.lifecycle.ProcessLifecycleOwner
1215import dagger.hilt.android.AndroidEntryPoint
1316import kotlinx.coroutines.CoroutineDispatcher
1417import kotlinx.coroutines.CoroutineScope
@@ -54,10 +57,15 @@ class LightningNodeService : Service() {
5457 @Inject
5558 lateinit var cacheStore: CacheStore
5659
60+ private var lifecycleObserver: AppLifecycleObserver ? = null
61+
5762 override fun onCreate () {
5863 super .onCreate()
5964 startForeground(ID_NOTIFICATION_NODE , createNotification())
6065 setupService()
66+ lifecycleObserver = AppLifecycleObserver ().also {
67+ ProcessLifecycleOwner .get().lifecycle.addObserver(it)
68+ }
6169 }
6270
6371 private fun setupService () {
@@ -145,6 +153,7 @@ class LightningNodeService : Service() {
145153
146154 override fun onDestroy () {
147155 Logger .debug(" onDestroy" , context = TAG )
156+ lifecycleObserver?.let { ProcessLifecycleOwner .get().lifecycle.removeObserver(it) }
148157 serviceScope.launch {
149158 lightningRepo.stop()
150159 serviceScope.cancel()
@@ -164,6 +173,24 @@ class LightningNodeService : Service() {
164173
165174 override fun onBind (intent : Intent ? ): IBinder ? = null
166175
176+ private inner class AppLifecycleObserver : DefaultLifecycleObserver {
177+ override fun onStart (owner : LifecycleOwner ) {
178+ serviceScope.launch {
179+ lightningRepo.disableBatterySavingMode()
180+ .onSuccess { Logger .debug(" Sync intervals exited battery saving mode" , context = TAG ) }
181+ .onFailure { Logger .warn(" Error setting sync intervals out of battery saving" , it, context = TAG ) }
182+ }
183+ }
184+
185+ override fun onStop (owner : LifecycleOwner ) {
186+ serviceScope.launch {
187+ lightningRepo.enableBatterySavingMode()
188+ .onSuccess { Logger .debug(" Sync intervals entered battery saving mode" , context = TAG ) }
189+ .onFailure { Logger .warn(" Error setting sync intervals set to battery saving" , it, context = TAG ) }
190+ }
191+ }
192+ }
193+
167194 companion object {
168195 const val CHANNEL_ID_NODE = " bitkit_notification_channel_node"
169196 const val TAG = " LightningNodeService"
0 commit comments