Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Guide to Foreground Services

Guide to Foreground Services

Foreground services are an essential component for executing long-running tasks on Android. However, as each new Android version introduces changes and limitations, implementing them correctly has become increasingly challenging. In this session, we will cover what a foreground service is, the changes introduced in recent Android versions, and how to update your apps to target the latest SDK versions. You will learn about different types of foreground services and common errors to avoid. We will also explore alternative approaches for handling background work. Additionally, we will take a practical look at how to correctly implement foreground services through a sample project. Walk away feeling confident you can leverage foreground services for long-running work in your apps.

Avatar for Domen Lanišnik

Domen Lanišnik

October 31, 2025
Tweet

More Decks by Domen Lanišnik

Other Decks in Programming

Transcript

  1. Because of the frequent API and behavioral changes 😅 API

    28 API 29 API 30 API 31 API 33 API 34 API 35 API 36
  2. Android 9 API 28 API 29 API 30 API 31

    API 33 API 34 API 35 API 36 • Introduced a new mandatory permission
 FOREGROUND_SERVICE 🆕
  3. Android 10 API 28 API 29 API 30 API 31

    API 33 API 34 API 35 API 36 • Introduced concept of foreground service type 🆕 • Mandatory for location 🧭
  4. Android 11 API 28 API 29 API 30 API 31

    API 33 API 34 API 35 API 36 • New 📸 and 🎤 foreground service types 🆕 • Restrictions to access 📸 and 🎤 when 
 FGS started from background 🤚
  5. Android 12 API 28 API 29 API 30 API 31

    API 33 API 34 API 35 API 36 • Restrictions on starting a FGS while in the background 🤚
  6. Android 13 API 28 API 29 API 30 API 31

    API 33 API 34 API 35 API 36 • Introduced noti fi cation permissions 🆕 • FGS noti fi cations can be dismissed 🔕
  7. Android 14 API 28 API 29 API 30 API 31

    API 33 API 34 API 35 API 36 • Foreground service type become mandatory ⚠ • Introduced new types 🆕
  8. Android 15 API 28 API 29 API 30 API 31

    API 33 API 34 API 35 API 36 • New type for media processing 🆕 • Boot completed receivers can’t launch some types of FGS 📵 • Introduced service timeouts ⏲
  9. Android 16 API 28 API 29 API 30 API 31

    API 33 API 34 API 35 API 36 • Background jobs started from a FGS must adhere to their respective runtime quotas ⚠ • New granular health permissions that
 a ff ect the health type 🏥
  10. Service • Perform long-running operations in the background ⏳ •

    No user interface 🙈 • Components can bind to it and interact with it ↔
  11. • User-initiated, time-sensitive tasks ⏱ • User-visible 📢 • Can

    run even after app is stopped 🏃 • Prioritized by the system ⬆ • Restricted background usage ⚠ Foreground Service
  12. Background Foreground • User-initiated tasks ⏱ • App-internal tasks 🧹

    • User-visible 📢 • Runs silently 🙈 • Even when app stopped 🏃 • While the app is running 🫠 • Prioritized by the system ⬆ • No prioritization ⬇ Restricted background usage ⚠
  13. • Simple string type ✍ • Declared in manifest and

    service 📝 • Describes the work 📝 Foreground Service Type
  14. ServiceCompat.startForeground( this, // service 1, // notification ID notification, //

    notification to display if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION } else { 0 } )
  15. Foreground Service Types camera 📷 connectedDevice 🎧 dataSync 🔄 health

    🩺 location 🧭 mediaPlayback ▶ mediaProjection 📺 microphone 🎤 phoneCall 📲 remoteMessaging 💬 shortService ⚠ specialUse ⚠ systemExempted ⚠ mediaProcessing 📀 https://developer.android.com/develop/background-work/services/fg-service-types
  16. • Ensures correct usage ✅ • Brings consistency across devices

    📱 • Defines runtime pre-requisites 📋 • Mandatory since Android 14❗ • Multiple types at once 🅰 🅱 Foreground Service Type
  17. • When interacting with an external device through BT, NFC,

    USB or WiFi 📲 • Several Runtime prerequisites (at least one of the following) ➡ connectedDevice Foreground Service Type
  18. • Declare one of the permissions in manifest: • CHANGE_NETWORK_STATE

    • CHANGE_WIFI_STATE • CHANGE_WIFI_MULTICAST_STATE, • NFC, • TRANSMIT_IR connectedDevice Foreground Service Type
  19. • OR one of the runtime permissions: • BLUETOOTH_CONNECT •

    BLUETOOTH_SCAN • BLUETOOTH_ADVERTISE • BLUETOOTH_SCAN • UWB_RANGING connectedDevice Foreground Service Type
  20. • OR call UsbManager.requestPermission() • Only after one of the

    following is true, can you start the service ✅ connectedDevice Foreground Service Type
  21. When can you start a FGS? • When app is

    in foreground ✅ • App transitions from a user-visible state 🏃 • App receives a high-priority message using FCM* 🚨 • App receives BOOT_COMPLETED action* 🥾 • … https://developer.android.com/develop/background-work/services/foreground-services#background-start-restriction-exemptions
  22. Notifications • Required when starting a FGS ❗ • Visible

    for the duration of the service 👀 • Requires channels, runtime permissions, … ⚠
  23. Play Console Declaration https://developer.android.com/develop/background-work/services/fg-service-types#google-play-enforcement • Describe app functionality 📝 •

    Describe user impact if task deferred or interrupted ⏹ • Include a link to a demo video 📹 • Select from a pre-defined list of use cases 📋
  24. No?

  25. • Continuous data transfer to external device -> CompanionDeviceManager 📲

    • Scanning for BT devices -> Bluetooth scan API 🔀 connectedDevice Foreground Service Type
  26. • From Android 15 for dataSync and mediaProcessing types ⏳

    • 6 hours per 24h per type ⏰ • System calls onTimeout(), giving you a few seconds to stop 🛑 Service Timeouts
  27. ANR ⚠ A foreground service of TYPE did not stop

    within its timeout: COMPONENT_NAME
  28. What if I need to respond to an event while

    app is in the background? 🤔
  29. • Broadcast message 🔊 • FCM Message 💬 • Alarm

    set by the app ⏰ Responding to an event
  30. No?

  31. How to create a Foreground Service? 1⃣ Create a Service

    and elevate it to foreground 🛠 2⃣ Use WorkManager to define a long- running Worker 🔧
  32. class ExampleForegroundService : Service() { override fun onStartCommand(…): Int {

    // TODO Start as foreground service return super.onStartCommand(intent, flags, startId) } }
  33. <!- - Request the general foreground service permission -- >

    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" / > <!- - Request the specific foreground service permission for each declared type --> <uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />
  34. 💥 java.lang.SecurityException: Starting FGS with type location targetSDK=34 requires permissions:

    all of the permissions allOf=true [android.permission.FOREGROUND_SERVICE_LOCATION]
  35. override fun onStartCommand(…): Int { ServiceCompat.startForeground( this, // service 1,

    // notification ID notification, // notification to display if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION } else { 0 } ) return super.onStartCommand(intent, flags, startId) }
  36. 💥 java.lang.SecurityException: Starting FGS with type location targetSDK=34 requires permissions:

    - all of the permissions allOf=true - [android.permission.FOREGROUND_SERVICE_LOCATION] - any of the permissions allOf=false - [android.permission.ACCESS_COARSE_LOCATION, android.permission.ACCESS_FINE_LOCATION]
  37. private val locationPermissionRequest = registerForActivityResult( ActivityResultContracts.RequestPermission() ) { granted ->

    if (granted) { / / Precise location access granted, service can run startForegroundService() } else { } } locationPermissionRequest.launch(ACCESS_FINE_LOCATION)
  38. override fun onStartCommand(…): Int { val fineLocationPermission = PermissionChecker.checkSelfPermission(this, ACCESS_FINE_LOCATION)

    if (fineLocationPermission ! = PermissionChecker.PERMISSION_GRANTED) { / / stop the service if we don't have the necessary permissions stopSelf() } else { startAsForegroundService() startLocationUpdates() } return super.onStartCommand(intent, flags, startId) }
  39. Stopping a service • stopForeground() for removing the service from

    foreground only 🔕 • stopSelf() for stopping the entire service 🛑
  40. Create FGS using WorkManager • Built-in support for long running

    workers ⏳ • Can run longer than 10 minutes 🕙 • Manages and runs a FGS on your behalf 😌 • Examples: tasks important to user 🧑💻, uploads/ downloads 🔁, local ML models 🤖, …
  41. <!- - Request the general foreground service permission -- >

    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" / > <!- - Request the specific foreground service permission for each declared type --> <uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />
  42. class ForegroundWorker( private val appContext: Context, params: WorkerParameters ) :

    CoroutineWorker(appContext, params) { override suspend fun doWork(): Result { setForeground(createForegroundInfo()) processLocationUpdates() return Result.success() } private fun createForegroundInfo(): ForegroundInfo { // TODO } }
  43. private fun createForegroundInfo(): ForegroundInfo { NotificationsHelper.createNotificationChannel(appContext) val notification = NotificationsHelper.buildNotification(appContext)

    return ForegroundInfo( 1, notification, if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION } else { 0 } ) }
  44. What to watch out for with WM? • FGS types

    and pre-requisites still apply ⚠ • Only use when the work is important to the user 🧑💻 • Also requires Play Store declaration 📝 • On Android 16 can exhaust the job quota ‼
  45. Sample app • Foreground service for location updates • Handling

    runtime permissions • Binding to the service to update UI • Stopping the service from the UI • Using WorkManager approach https://github.com/landomen/ForegroundServiceSamples
  46. Why so much friction? • More intentional usage 🧐 •

    Use purpose-built APIs and
 WorkManager instead 🎯 • Protect users 🛡
  47. Summary • Foreground Services can be tricky 😅 • Consider

    other approaches first 📋 • Use the appropriate type to ensure compliancy ✅ • Two ways to create a FGS 🏗