Bound Service
Google documentation for more information
In AndroidManifest.xml create service:
Create MyService.kt class:
In MainActivity.kt:
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”.
Background Service
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.
Foreground Service
Create permission in AndroidManifest.xml:
Modify MyService.kt:
Just add Create and Display functions, and start and stop service in start and stop audio functions.
Foreground Service: Add buttons to Notification
Modify MyService.kt:
The result would be the Notification with Play and Stop buttons:
Bonus: Add styling to notification
Let's add an image to notification. Modify displayForegroundNotification() function in MyService.kt class: