ARTICLE AD BOX
I am working on a Wear OS app, which monitors the users data 24/7. The app is made for Samsung devices as part of a study. The data includes some health data and location data. My current setup works okay, but I run into consistency problems. Sometimes the data collection stops or slows down.
When the app opens, a monitoring foreground service is started:
class MainActivity: ComponentActivity() { override fun onStart() { checkForegroundPermissions() // When permissions are given launchForegroundService is run } private fun launchForegroundService() { val serviceIntent = Intent(this, ForegroundMonitoringService::class.java) startForegroundService(serviceIntent) bindService(serviceIntent, foregroundOnlyServiceConnection, BIND_AUTO_CREATE) } }I launch it as a bound service, so I have access to the services methods
Within the service I start it as a foreground service:
class ForegroundMonitoringService : Service() { private val serviceJob = SupervisorJob() private val serviceScope = CoroutineScope(serviceJob + Dispatchers.Default) override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { super.onStartCommand(intent, flags, startId) startForeground() startMonitoringJob() return START_STICKY } private fun startForeground() { val serviceTypes = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { FOREGROUND_SERVICE_TYPE_LOCATION or FOREGROUND_SERVICE_TYPE_HEALTH } else { 0 } ServiceCompat.startForeground( this, SERVICE_ID, generateNotification(isMonitoring = false), serviceTypes ) } private fun startMonitoringJob() { while (isActive) { monitoringJob?.cancel() monitoringJob = serviceScope.launch { val result = monitoringRepository.sendData() result .onSuccess {} .onFailure { error -> ...} delay(SEND_DATA_INTERVAL) } } } }The monitoring repository collects 4-6 flows of sensor data and combines them into one data class, which is made into JSON and sent to our server at SEND_DATA_INTERVAL.
The monitoring repository has a backup mechanism, so if the data isn’t sent because of network issues, data is stored locally and a WorkManager attempts to send the accumulated data when network is available again.
I am not sure what is stopping or slowing down the monitoring exactly. I am aware that the system is going to fight the app a bit, but monitoring is vital to our experiments, so data integrity is more important than device health.
I have seen solutions like wakelocks and alert managers or work managers that will restart the service if it stops, but the posts that suggests them are getting old, so I am not sure this is the best solution anymore.
My question is: How can I reliably detect, prevent, and recover from my Android foreground service being killed, and how can I test or verify that it remains running over long periods without manual monitoring?
