Long-Running Services in Android

Daniyar
Oct 19, 2020
Photo by Kate Townsend on Unsplash

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”.

git link

Background Service

In MainActivity.kt just add startService(…) function

In MyService.kt override onStartCommand(…) function:

git link

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.

git link

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.

git link

Foreground Service: Add buttons to Notification

Modify MyService.kt:

The result would be the Notification with Play and Stop buttons:

git link

Bonus: Add styling to notification

Let's add an image to notification. Modify displayForegroundNotification() function in MyService.kt class:

git link

--

--

Daniyar

Ex- Google Certified Associate Android Developer