Long-Running Services in Android

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

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Daniyar

Daniyar

Google Certified Associate Android Developer