I want to have an app that can receive event updates from the MotionSensors, even if the app is in the background. The problem is that android kills any service if the app has been in the background for one minute.
- Deactivating battery optimization did not help
- I can't really launch it as a Foreground service (which would not be killed) because one just registers the listeners to the already existing service (according to my knowledge) using
val sensorsManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
sensorManager.registerListener( .. )
Does anyone know a simple way of fixing this behaviour? Either using code or better, disabling some setting on android. Thanks.
CodePudding user response:
First of all, in order to run it permanently, there must be a notification that it is running permanently.This notification is permanent and you cannot turn it off from the notification section.
Service.kt
private fun parmanentNotification() {
val notification=NotificationCompat.Builder(this,channelId)
.setSmallIcon(R.drawable.ic_stat_name)
.setContentTitle("The application is running")
.setContentText("Android motion sensor working")
.build()
startForeground(1,notification)
}
This is how we start my service
@RequiresApi(Build.VERSION_CODES.M)
override fun onStart() {
val notificationIntent = Intent(this, YouServiceName::class.java)
startService(notificationIntent)
super.onStart()
}