Foreground Services in Android 14: What’s Changing? | by Konstantin Merenkov

In order to make an app with foreground services Android 14 compatible, there are three things you need to do:

  1. Set service type in Manifest
  2. Specify new permissions
  3. Update startForeground() function with foregroundServiceType parameter

Set service type in Manifest

To declare a foreground service type, add the android:foregroundServiceType attribute to the <service> element in your manifest. For example, the following code declares a foreground service of type dataSync:

<service
android:name=".YourForegroundService"
android:foregroundServiceType="dataSync" />

All available types can be found here.

If service type is not specified, you will get an exception: MissingForegroundServiceTypeException: Starting FGS without a type

Specify new permissions

You must also specify the appropriate permission for the foreground service type. For example, the following code requests the permission for foreground services of type dataSync:

<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />

Does it mean that you don’t need usual FOREGROUND_SERVICE permission anymore?

Yes, you are right. All you need is to replace the old FOREGROUND_SERVICE permission with the new one (or a few, if you have services with different types).

Update startForeground function

Lastly, you also need to specify the service type in startForeground() function which is located in onStartCommand() function of the service class.

Specifying the type requires Android Q, so you’ll have to wrap it into a statement in order to use the old startForeground() for android versions lower than Q. If your minSDK is 29 or higher — just use the one with foreground service type.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) 
startForeground(1, notification.build(), ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION)
else
startForeground(1, notification.build(),)

Next Post

How To Properly Forecast Email Revenue

Unlock the secrets to accurately forecast your email revenue with this comprehensive guide. In the digital age, email marketing has become an integral part of business strategies. It not only helps to build brand awareness but also generates revenue. However, to maximize the potential of email marketing, it is essential […]
How To Properly Forecast Email Revenue

You May Like