Search code examples
androidserviceandroid-api-levels

Foreground service in API Level 24 - Android 7.0 Nougat


My question is specific to API LEVEL 24 - Android 7.0 Nougat. I am trying to find the most appropriate and futureproof way to start a sticky foreground service. To sum up: - The service needs to be started from an activity after a button press - A (sticky - this will be handled by notification flags) notification will be created

In API level 26, we can call startForegroundService(service, notification) and the service is automatically corellated to the notification. However in API level 24, the service is started with startService(service) and the notification is displayed by calling NotificationManagerCompat's notify method. How can we let the OS know that the notification is related to the service, so the service is considered a foreground service, that the OS will never kill by itself.

Note: the reason I want this implementation is to be futureproof. This service needs location updates and starting from API Level 26, only foreground services (with sticky notification) are able to receive real time updates (https://developer.android.com/about/versions/oreo/background-location-limits).


Solution

  • How can we let the OS know that the notification is related to the service, so the service is considered a foreground service

    Call startForeground() in the service, supplying the Notification. You need to do this on Android 8.0+ as well.

    that the OS will never kill by itself

    That has never been the case. It simply makes it less likely that Android will terminate your process.