In this video we will learn how to start a foreground service in Android, which runs independently from other app components (like activities), but displays a persistent notification to the user as long as it is running.
We create our foreground service by extending the Service class and overriding onStartCommand, where we then promote our service to the foreground by calling startForeground and passing a notification to it, which we build with the NotificationCompat.Builder.
With target API level 26 (Android Oreo) or higher, we have to create notification channels in order to be able to display notifications, and we will do this is in the Application class.
Depending if we want to restart the service if the system kills it, we return either START_STICKY, START_NOT_STICKY or START_REDELIVER_INTENT from onStartCommand.
Additional we can override onCreate and onDestroy, where we can do an initial setup and a cleanup. We also have to override onBind, but since we are creating a started service and not a bound service, we can just ignore this method and return null.
We register our service in the AndroidManifest.xml file and then we can start it by calling startService, startForegroundService or ContextCompat.startForegroundService, where we have to pass an intent, which can optionally contain data in form of extras.
We stop the service by calling either stopSelf from within, or stopService from another app component.
Subscribe to my channel:
Want more Android tutorials? Check my playlist section:
Follow me on social media: