Le type de service au premier plan doit être indiqué

Pour aider les développeurs à définir des services de premier plan destinés aux utilisateurs, Android 10 a introduit l'attribut android:foregroundServiceType dans l'élément <service>.

Si votre application cible Android 14, elle doit spécifier les types de services de premier plan appropriés. Comme dans les versions précédentes d'Android, vous pouvez combiner plusieurs types. Cette liste présente les types de services de premier plan disponibles :

Si un cas d'utilisation dans votre application n'est associé à aucun de ces types, nous vous recommandons fortement de migrer votre logique pour utiliser WorkManager ou les tâches de transfert de données lancé par l'utilisateur.

Les types health, remoteMessaging, shortService, specialUse et systemExempted sont nouveaux sur Android 14.

L'extrait de code suivant fournit un exemple de déclaration de type de service de premier plan dans le fichier manifeste :

<manifest ...>
  <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
  <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
    <application ...>
      <service
          android:name=".MyMediaPlaybackService"
          android:foregroundServiceType="mediaPlayback"
          android:exported="false">
      </service>
    </application>
</manifest>

Si une application qui cible Android 14 ne définit pas de types pour un service donné dans le fichier manifeste, le système génère MissingForegroundServiceTypeException lors de l'appel de startForeground() pour ce service.

Déclarer une nouvelle autorisation pour utiliser les types de services de premier plan

Si les applications qui ciblent Android 14 utilisent un service de premier plan, elles doivent déclarer une autorisation spécifique, basée sur le type de service de premier plan, introduite par Android 14. Ces autorisations apparaissent dans les sections intitulées "Autorisation que vous devez déclarer dans votre fichier manifeste" de la section Cas d'utilisation prévus et mesures d'application pour chaque type de service de premier plan sur cette page.

Toutes les autorisations sont définies comme des autorisations normales et sont accordées par défaut. Les utilisateurs ne peuvent pas les révoquer.

Inclure le type de service de premier plan lors de l'exécution

Une bonne pratique pour les applications qui lancent des services de premier plan consiste à utiliser la version ServiceCompat de startForeground() (disponible dans androidx-core 1.12 et versions ultérieures), dans laquelle vous transmettez un entier bit à bit de types de service de premier plan. Vous pouvez choisir de transmettre une ou plusieurs valeurs de type.

En règle générale, vous ne devez déclarer que les types requis pour un cas d'utilisation particulier. Cela permet de répondre plus facilement aux attentes du système pour chaque type de service de premier plan. Si un service de premier plan est démarré avec plusieurs types, il doit respecter les exigences d'application des plates-formes de tous les types.

ServiceCompat.startForeground(0, notification, FOREGROUND_SERVICE_TYPE_LOCATION)

Si le type de service de premier plan n'est pas spécifié dans l'appel, il utilise par défaut les valeurs définies dans le fichier manifeste. Si vous n'avez pas spécifié le type de service dans le fichier manifeste, le système génère MissingForegroundServiceTypeException.

Si le service de premier plan a besoin de nouvelles autorisations après son lancement, vous devez appeler à nouveau startForeground() et ajouter les nouveaux types de services. Par exemple, supposons qu'une application de fitness exécute un service de suivi de la course à pied qui a toujours besoin des informations location, mais qui peut ou non avoir besoin d'autorisations media. Vous devez déclarer à la fois location et mediaPlayback dans le fichier manifeste. Si un utilisateur démarre une exécution et souhaite simplement suivre sa position, votre application doit appeler startForeground() et ne transmettre que le type de service location. Ensuite, si l'utilisateur souhaite commencer à lire un contenu audio, appelez à nouveau startForeground() et transmettez location|mediaPlayback.

Vérifications de l'exécution du système

The system checks for proper use of foreground service types and confirms that the app has requested the proper runtime permissions or uses the required APIs. For instance, the system expects apps that use the foreground service type FOREGROUND_SERVICE_TYPE_LOCATION type to request either ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION.

This implies that apps must follow a very specific order of operations when requesting permissions from the user and starting foreground services. Permissions must be requested and granted before the app attempts to call startForeground(). Apps that request the appropriate permissions after the foreground service has been started must change this order of operations and request the permission before starting the foreground service.

The specifics of platform enforcement appear in the sections labeled "runtime requirements" in the intended use cases and enforcement for each foreground service type section on this page.

Cas d'utilisation prévus et application forcée pour chaque type de service de premier plan

Pour utiliser un type de service de premier plan donné, vous devez déclarer une autorisation particulière dans votre fichier manifeste, respecter des exigences d'exécution spécifiques et votre application doit respecter l'un des ensembles de cas d'utilisation prévus pour ce type. Les sections suivantes décrivent les autorisations que vous devez déclarer, les conditions préalables d'exécution et les cas d'utilisation prévus pour chaque type.

Appareil photo

Type de service de premier plan à déclarer dans le fichier manifeste sous android:foregroundServiceType
camera
Autorisation à déclarer dans votre fichier manifeste
FOREGROUND_SERVICE_CAMERA
Constante à transmettre à startForeground()
FOREGROUND_SERVICE_TYPE_CAMERA
Conditions préalables d'exécution

Demander l'autorisation d'exécution CAMERA et l'obtenir

Remarque:L'autorisation d'exécution CAMERA est soumise à des restrictions d'utilisation. Pour cette raison, vous ne pouvez pas créer de service de premier plan camera lorsque votre application est en arrière-plan, à quelques exceptions près. Pour en savoir plus, consultez la section Restrictions concernant le démarrage de services de premier plan nécessitant des autorisations en cours d'utilisation.

Description

Continuez à avoir accès à la caméra en arrière-plan, pour les applications de chat vidéo permettant d'effectuer plusieurs tâches en même temps, par exemple.

Appareil connecté

Type de service de premier plan à déclarer dans le fichier manifeste sous
android:foregroundServiceType
connectedDevice
Autorisation à déclarer dans votre fichier manifeste
FOREGROUND_SERVICE_CONNECTED_DEVICE
Constante à transmettre à startForeground()
FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE
Conditions préalables d'exécution

Vous devez remplir l'une des conditions suivantes :

Description

Interactions avec des appareils externes nécessitant une connexion Bluetooth, NFC, IR, USB ou réseau.

Autres solutions

Si votre application doit effectuer un transfert de données continu vers un appareil externe, envisagez d'utiliser le gestionnaire d'appareils associés à la place. Utilisez l'API de présence de l'appareil associé pour que votre application reste en cours d'exécution lorsque l'appareil associé est à portée.

Si votre application doit rechercher des appareils Bluetooth, envisagez plutôt d'utiliser l'API de recherche Bluetooth.

Synchroniser les données

Foreground service type to declare in manifest under
android:foregroundServiceType
dataSync
Permission to declare in your manifest
FOREGROUND_SERVICE_DATA_SYNC
Constant to pass to startForeground()
FOREGROUND_SERVICE_TYPE_DATA_SYNC
Runtime prerequisites
None
Description

Data transfer operations, such as the following:

  • Data upload or download
  • Backup-and-restore operations
  • Import or export operations
  • Fetch data
  • Local file processing
  • Transfer data between a device and the cloud over a network
Alternatives

See Alternatives to data sync foreground services for detailed information.

Santé

要在清单中的以下位置声明的前台服务类型
android:foregroundServiceType
health
在清单中声明的权限
FOREGROUND_SERVICE_HEALTH
要传递给 startForeground() 的常量
FOREGROUND_SERVICE_TYPE_HEALTH
运行时前提条件

必须至少满足以下其中一个条件:

注意BODY_SENSORS 和基于传感器的读取运行时权限受“在使用时”限制。因此,除非您已获得 BODY_SENSORS_BACKGROUND(API 级别 33 到 35)或 READ_HEALTH_DATA_IN_BACKGROUND(API 级别 36 及更高级别)权限,否则您无法创建在应用处于后台运行时使用身体传感器的 health 前台服务。如需了解详情,请参阅与启动需要使用时权限的前台服务相关的限制

说明

为健身类别的应用(例如锻炼追踪器)提供支持的所有长时间运行的用例。

Localisation

Foreground service type to declare in manifest under
android:foregroundServiceType
location
Permission to declare in your manifest
FOREGROUND_SERVICE_LOCATION
Constant to pass to startForeground()
FOREGROUND_SERVICE_TYPE_LOCATION
Runtime prerequisites

The user must have enabled location services and the app must be granted at least one of the following runtime permissions:

Note: In order to check that the user has enabled location services as well as granted access to the runtime permissions, use PermissionChecker#checkSelfPermission()

Note: The location runtime permissions are subject to while-in-use restrictions. For this reason, you cannot create a location foreground service while your app is in the background, unless you've been granted the ACCESS_BACKGROUND_LOCATION runtime permission. For more information, see Restrictions on starting foreground services that need while-in-use permissions.

Description

Long-running use cases that require location access, such as navigation and location sharing.

Alternatives

If your app needs to be triggered when the user reaches specific locations, consider using the geofence API instead.

Contenus multimédias

Foreground service type to declare in manifest under
android:foregroundServiceType
mediaPlayback
Permission to declare in your manifest
FOREGROUND_SERVICE_MEDIA_PLAYBACK
Constant to pass to startForeground()
FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK
Runtime prerequisites
None
Description
Continue audio or video playback from the background. Support Digital Video Recording (DVR) functionality on Android TV.
Alternatives
If you're showing picture-in-picture video, use Picture-in-Picture mode.

Projection multimédia

要在清单中的以下位置声明的前台服务类型
android:foregroundServiceType
mediaProjection
在清单中声明的权限
FOREGROUND_SERVICE_MEDIA_PROJECTION
要传递给 startForeground() 的常量
FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION
运行时前提条件

在启动前台服务之前调用 createScreenCaptureIntent() 方法。这样做会向用户显示权限通知;用户必须先授予权限,您才能创建服务。

创建前台服务后,您可以调用 MediaProjectionManager.getMediaProjection()

说明

使用 MediaProjection API 将内容投影到非主要显示屏或外部设备。这些内容不必全都为媒体内容。

替代方案

如需将媒体流式传输到其他设备,请使用 Google Cast SDK

Micro

要在清单中的以下位置声明的前台服务类型
android:foregroundServiceType
microphone
在清单中声明的权限
FOREGROUND_SERVICE_MICROPHONE
要传递给 startForeground() 的常量
FOREGROUND_SERVICE_TYPE_MICROPHONE
运行时前提条件

请求并获得 RECORD_AUDIO 运行时权限。

注意RECORD_AUDIO 运行时权限受使用时限制的约束。因此,除少数例外情况外,您无法在应用在后台运行时创建 microphone 前台服务。如需了解详情,请参阅与启动需要使用时权限的前台服务相关的限制

说明

在后台继续捕获麦克风内容,例如录音器或通信应用。

Appel téléphonique

Foreground service type to declare in manifest under
android:foregroundServiceType
phoneCall
Permission to declare in your manifest
FOREGROUND_SERVICE_PHONE_CALL
Constant to pass to startForeground()
FOREGROUND_SERVICE_TYPE_PHONE_CALL
Runtime prerequisites

At least one of these conditions must be true:

  • App is the default dialer app through the ROLE_DIALER role.
Description

Continue an ongoing call using the ConnectionService APIs.

Alternatives

If you need to make phone, video, or VoIP calls, consider using the android.telecom library.

Consider using CallScreeningService to screen calls.

Messagerie à distance

Type de service de premier plan à déclarer dans le fichier manifeste sous
android:foregroundServiceType
remoteMessaging
Autorisation à déclarer dans votre fichier manifeste
FOREGROUND_SERVICE_REMOTE_MESSAGING
Constante à transmettre à startForeground()
FOREGROUND_SERVICE_TYPE_REMOTE_MESSAGING
Conditions préalables d'exécution
Aucune
Description
Transférez des messages d'un appareil à un autre. Contribue à la continuité des tâches de messagerie d'un utilisateur lorsqu'il change d'appareil.

Service court

Foreground service type to declare in manifest under
android:foregroundServiceType
shortService
Permission to declare in your manifest
None
Constant to pass to startForeground()
FOREGROUND_SERVICE_TYPE_SHORT_SERVICE
Runtime prerequisites
None
Description

Quickly finish critical work that cannot be interrupted or postponed.

This type has some unique characteristics:

  • Can only run for a short period of time (about 3 minutes).
  • No support for sticky foreground services.
  • Cannot start other foreground services.
  • Doesn't require a type-specific permission, though it still requires the FOREGROUND_SERVICE permission.
  • A shortService can only change to another service type if the app is currently eligible to start a new foreground service.
  • A foreground service can change its type to shortService at any time, at which point the timeout period begins.

The timeout for shortService begins from the moment that Service.startForeground() is called. The app is expected to call Service.stopSelf() or Service.stopForeground() before the timeout occurs. Otherwise, the new Service.onTimeout() is called, giving apps a brief opportunity to call stopSelf() or stopForeground() to stop their service.

A short time after Service.onTimeout() is called, the app enters a cached state and is no longer considered to be in the foreground, unless the user is actively interacting with the app. A short time after the app is cached and the service has not stopped, the app receives an ANR. The ANR message mentions FOREGROUND_SERVICE_TYPE_SHORT_SERVICE. For these reasons, it's considered best practice to implement the Service.onTimeout() callback.

The Service.onTimeout() callback doesn't exist on Android 13 and lower. If the same service runs on such devices, it doesn't receive a timeout, nor does it ANR. Make sure that your service stops as soon as it finishes the processing task, even if it hasn't received the Service.onTimeout() callback yet.

It's important to note that if the timeout of the shortService is not respected, the app will ANR even if it has other valid foreground services or other app lifecycle processes running.

If an app is visible to the user or satisfies one of the exemptions that allow foreground services to be started from the background, calling Service.StartForeground() again with the FOREGROUND_SERVICE_TYPE_SHORT_SERVICE parameter extends the timeout by another 3 minutes. If the app isn't visible to the user and doesn't satisfy one of the exemptions, any attempt to start another foreground service, regardless of type, causes a ForegroundServiceStartNotAllowedException.

If a user disables battery optimization for your app, it's still affected by the timeout of shortService FGS.

If you start a foreground service that includes the shortService type and another foreground service type, the system ignores the shortService type declaration. However, the service must still adhere to the prerequisites of the other declared types. For more information, see the Foreground services documentation.

Utilisation spéciale

Foreground service type to declare in manifest under
android:foregroundServiceType
specialUse
Permission to declare in your manifest
FOREGROUND_SERVICE_SPECIAL_USE
Constant to pass to startForeground()
FOREGROUND_SERVICE_TYPE_SPECIAL_USE
Runtime prerequisites
None
Description

Covers any valid foreground service use cases that aren't covered by the other foreground service types.

In addition to declaring the FOREGROUND_SERVICE_TYPE_SPECIAL_USE foreground service type, developers should declare use cases in the manifest. To do so, they specify the <property> element within the <service> element. These values and corresponding use cases are reviewed when you submit your app in the Google Play Console. The use cases you provide are free-form, and you should make sure to provide enough information to let the reviewer see why you need to use the specialUse type.

<service android:name="fooService" android:foregroundServiceType="specialUse">
  <property android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
      android:value="explanation_for_special_use"/>
</service>

Système exempté

Foreground service type to declare in manifest under
android:foregroundServiceType
systemExempted
Permission to declare in your manifest
FOREGROUND_SERVICE_SYSTEM_EXEMPTED
Constant to pass to startForeground()
FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED
Runtime prerequisites
None
Description

Reserved for system applications and specific system integrations, to continue to use foreground services.

To use this type, an app must meet at least one of the following criteria:

  • Device is in demo mode state
  • App is a Device Owner
  • App is a Profiler Owner
  • Safety Apps that have the ROLE_EMERGENCY role
  • Device Admin apps
  • Apps holding SCHEDULE_EXACT_ALARM or USE_EXACT_ALARM permission and are using Foreground Service to continue alarms in the background, including haptics-only alarms.
  • VPN apps (configured using Settings > Network & Internet > VPN)

    Otherwise, declaring this type causes the system to throw a ForegroundServiceTypeNotAllowedException.

Application des règles Google Play pour l'utilisation des types de services de premier plan

Si votre application cible Android 14 ou une version ultérieure, vous devez déclarer les types de services de premier plan de votre application sur la page "Contenu de l'application" de la Play Console (Règles > Contenu de l'application). Pour en savoir plus sur la déclaration de vos types de services de premier plan dans la Play Console, consultez Comprendre les exigences liées aux services de premier plan et à l'intent plein écran.