Long-Running Services in Android
In AndroidManifest.xml create service:
Create MyService.kt class:
The main point here, that while the activity is on focus, the service will continue working.
The Logcat result will be:
When the app starts - it will call "Service connecting".
When the button is clicked - it will call “Starting Action”.
In MainActivity.kt just add startService(…) function
In MyService.kt override onStartCommand(…) function:
Background Service: with play music example
In MyService.kt create MediaPlayer object, then create 2 functions that will Play and Stop MediaPlayer
In MainActivity.kt on set on 2 buttons click listeners that will call Start and Stop audio in service.
Create permission in AndroidManifest.xml:
Just add Create and Display functions, and start and stop service in start and stop audio functions.
Foreground Service: Add buttons to Notification
The result would be the Notification with Play and Stop buttons: