I am trying to stop the service when the app is exited, however it continues to run for a minute or two.
This is the code I rely on:
override fun onTaskRemoved(rootIntent: Intent?) {
stopSelf()
super.onTaskRemoved(rootIntent)
}
if I were to stop it manually with a button click and then exit the app everything works. I can see that the process exits immediately in android studio.
Button listener in MainActivity:
binding.mainBtn.setOnClickListener {
isConnected = if(!isConnected && checkPermission()) {
startService(Intent(this, MyForegroundService::class.java))
binding.mainBtn.setImageResource(R.drawable.ic_baseline_stop_24)
true
} else {
stopService(Intent(this, MyForegroundService::class.java))
binding.mainBtn.setImageResource(R.drawable.ic_baseline_play_arrow_24)
false
}
}
The manifest file looks like this:
<service
android:name=".services.MyForegroundService"
android:enabled="true"
android:exported="false"
android:foregroundServiceType="microphone"/>