I am implementing a dummy foreground service (to see how it works) in an android project. The purpose is to see if there are issues with the execution (in cases such as the phone screen goes off etch.).
Here are some parts of the service:
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)
writeStringToFile("Within Service...starting \n")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O)
startMyOwnForeground()
else
startForeground(1, Notification())
}
setCountdownTimer()
// Schedule the periodic alarm to keep the service alive
val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
val alarmIntent = Intent(this, YourAlarmReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0)
val intervalMillis = 10 * 60 * 1000 // 10 minutes
val triggerTime = SystemClock.elapsedRealtime() + intervalMillis
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmManager.setExactAndAllowWhileIdle(
AlarmManager.ELAPSED_REALTIME_WAKEUP,
triggerTime,
pendingIntent
)
} else {
alarmManager.setExact(
AlarmManager.ELAPSED_REALTIME_WAKEUP,
triggerTime,
pendingIntent
)
}
val pm = getSystemService(POWER_SERVICE) as PowerManager
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"sensorApp::wakelock")
wl!!.acquire()
//register reciever related with power service identification
powerModeReceiver = PowerModeReceiver()
val intentFilter = IntentFilter().apply {
addAction(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED)
addAction("android.os.action.DEVICE_IDLE_MODE_CHANGED")
}
this.registerReceiver(powerModeReceiver, intentFilter)
val scope = CoroutineScope(Dispatchers.Default)
// Create the timer flow
val timer = (0..Int.MAX_VALUE)
.asSequence()
.asFlow()
.onEach { delay(1_000) } // specify delay
scope.launch {
timer.collect {
storeLogData()
}
}
return START_REDELIVER_INTENT
}
Howerever it appears that the service is re-starting by itself (as the countdowntimer that i have implemented switches back to 0 - though the service is not destroyed - i am not getting any log in the onDestroy method). What could be the reason for this? I have also implemented a powerModeReciever that checks if the app is entering Power Save / Idle mode, but not such modes appear to get triggered when the service is restarting.
Any help is appreciated!
Lampros