@@ -25,6 +25,7 @@ import androidx.navigation.compose.rememberNavController
2525import androidx.navigation.toRoute
2626import dagger.hilt.android.AndroidEntryPoint
2727import kotlinx.coroutines.CoroutineScope
28+ import kotlinx.coroutines.flow.map
2829import kotlinx.coroutines.launch
2930import kotlinx.serialization.Serializable
3031import to.bitkit.androidServices.LightningNodeService
@@ -45,6 +46,7 @@ import to.bitkit.ui.sheets.NewTransactionSheet
4546import to.bitkit.ui.theme.AppThemeSurface
4647import to.bitkit.ui.utils.composableWithDefaultTransitions
4748import to.bitkit.ui.utils.enableAppEdgeToEdge
49+ import to.bitkit.utils.Logger
4850import to.bitkit.viewmodels.ActivityListViewModel
4951import to.bitkit.viewmodels.AppViewModel
5052import to.bitkit.viewmodels.BackupsViewModel
@@ -78,7 +80,7 @@ class MainActivity : FragmentActivity() {
7880 importance = NotificationManager .IMPORTANCE_LOW
7981 )
8082 appViewModel.handleDeeplinkIntent(intent)
81- startForegroundService( Intent ( this , LightningNodeService :: class .java))
83+
8284 installSplashScreen()
8385 enableAppEdgeToEdge()
8486 setContent {
@@ -89,6 +91,21 @@ class MainActivity : FragmentActivity() {
8991 ) {
9092 val scope = rememberCoroutineScope()
9193 val isRecoveryMode by walletViewModel.isRecoveryMode.collectAsStateWithLifecycle()
94+ val notificationsGranted by settingsViewModel.notificationsGranted.collectAsStateWithLifecycle()
95+ val walletExists by walletViewModel.walletState
96+ .map { it.walletExists }
97+ .collectAsStateWithLifecycle(initialValue = walletViewModel.walletExists)
98+
99+ LaunchedEffect (
100+ walletExists,
101+ isRecoveryMode,
102+ notificationsGranted
103+ ) {
104+ if (walletExists && ! isRecoveryMode && notificationsGranted) {
105+ tryStartForegroundService()
106+ }
107+ }
108+
92109 if (! walletViewModel.walletExists && ! isRecoveryMode) {
93110 OnboardingNav (
94111 startupNavController = rememberNavController(),
@@ -170,6 +187,27 @@ class MainActivity : FragmentActivity() {
170187 setIntent(intent)
171188 appViewModel.handleDeeplinkIntent(intent)
172189 }
190+
191+ override fun onDestroy () {
192+ super .onDestroy()
193+ if (! settingsViewModel.notificationsGranted.value) {
194+ runCatching {
195+ stopService(Intent (this , LightningNodeService ::class .java))
196+ }
197+ }
198+ }
199+
200+ /* *
201+ * Attempts to start the LightningNodeService if it's not already running.
202+ */
203+ private fun tryStartForegroundService () {
204+ runCatching {
205+ Logger .debug(" Attempting to start LightningNodeService" , context = " MainActivity" )
206+ startForegroundService(Intent (this , LightningNodeService ::class .java))
207+ }.onFailure { error ->
208+ Logger .error(" Failed to start LightningNodeService" , error, context = " MainActivity" )
209+ }
210+ }
173211}
174212
175213@Composable
0 commit comments