In
this article I gave an example on how to start foreground service, but not how to stop it.
In MyService.kt add the code:
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent?.action.equals("stopForeground")) {
stopForeground(true)
stopSelfResult(startId)
}
return super.onStartCommand(intent, flags, startId)
}
and in MainActivity.kt I have added new button and onClick:
@RequiresApi(Build.VERSION_CODES.O)
fun stopForegroundServiceAndBroadcastReceiverClick(view: View) {
val intent = Intent(this, MyService::class.java)
intent.action = "stopForeground"
startForegroundService(intent)
}
From
here.