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:

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.

startForeground(1,, ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION)
} else {

Source link