À partir d'Android 14 (niveau d'API 34), vous devez déclarer un type de service approprié pour chaque service de premier plan. Cela signifie que vous devez déclarer le type de service dans le fichier manifeste de votre application, et demander également l'autorisation de service de premier plan appropriée pour ce type (en plus de demander l'autorisation FOREGROUND_SERVICE
). De plus, selon le type de service de premier plan, vous devrez peut-être demander des autorisations d'exécution avant de lancer le service.
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- 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 de déclarer dans votre fichier manifeste
FOREGROUND_SERVICE_CONNECTED_DEVICE
- Constante à transmettre à
startForeground()
FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE
- Conditions requises pour l'environnement d'exécution
Vous devez remplir l'une des conditions suivantes :
Déclarez au moins l'une des autorisations suivantes dans votre fichier manifeste :
Demandez et recevez au moins l'une des autorisations d'exécution suivantes:
Appeler
UsbManager.requestPermission()
- 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 plutôt d'utiliser le gestionnaire d'appareils associés. Utilisez l'API de présence d'appareil associé pour permettre à votre application de rester exécutée lorsque l'appareil associé est à portée.
Si votre application doit rechercher des appareils Bluetooth, envisagez plutôt d'utiliser l'API Bluetooth Scan.
Synchroniser les données
- 要在清单中的以下位置声明的前台服务类型
android:foregroundServiceType
dataSync
- 在清单中声明的权限
FOREGROUND_SERVICE_DATA_SYNC
- 要传递给
startForeground()
的常量 FOREGROUND_SERVICE_TYPE_DATA_SYNC
- 运行时前提条件
- 无
- 说明
数据传输操作,例如:
- 数据上传或下载
- 备份和恢复操作
- 导入或导出操作
- 获取数据
- 本地文件处理
- 通过网络在设备和云端之间传输数据
- 替代方案
如需了解详情,请参阅数据同步前台服务的替代方案。
Santé
- Type de service de premier plan à déclarer dans le fichier manifeste sous
android:foregroundServiceType
health
- Autorisation à déclarer dans votre fichier manifeste
FOREGROUND_SERVICE_HEALTH
- Constante à transmettre à
startForeground()
FOREGROUND_SERVICE_TYPE_HEALTH
- Conditions préalables d'exécution
Vous devez remplir l'une des conditions suivantes :
Déclarez l'autorisation
HIGH_SAMPLING_RATE_SENSORS
dans votre fichier manifeste.Demandez et obtenez au moins l'une des autorisations d'exécution suivantes:
- Description
Tous les cas d'utilisation de longue durée pour prendre en charge les applications de la catégorie "Remise en forme", tels que les coachs électroniques d'entraînement.
Localisation
- Type de service de premier plan à déclarer dans le fichier manifeste sous
android:foregroundServiceType
location
- Autorisation à déclarer dans votre fichier manifeste
FOREGROUND_SERVICE_LOCATION
- Constante à transmettre à
startForeground()
FOREGROUND_SERVICE_TYPE_LOCATION
- Conditions préalables d'exécution
L'utilisateur doit avoir activé les services de localisation, et l'application doit disposer d'au moins l'une des autorisations d'exécution suivantes:
- Description
Cas d'utilisation de longue durée nécessitant un accès à la position, tels que la navigation et le partage de position.
- Autres solutions
Si votre application doit être déclenchée lorsque l'utilisateur atteint des emplacements spécifiques, envisagez plutôt d'utiliser l'API Geofence.
Contenus multimédias
- Type de service de premier plan à déclarer dans le fichier manifeste sous
android:foregroundServiceType
mediaPlayback
- Autorisation à déclarer dans votre fichier manifeste
FOREGROUND_SERVICE_MEDIA_PLAYBACK
- Constante à transmettre à
startForeground()
FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK
- Conditions préalables d'exécution
- Aucune
- Description
Permet de poursuivre la lecture audio ou vidéo en arrière-plan. Prend en charge la fonctionnalité d'enregistrement vidéo numérique (DVR) sur Android TV.
- Autres solutions
Si vous diffusez une vidéo en mode Picture-in-picture, utilisez le mode Picture-in-picture.
Traitement multimédia
- Foreground service type to declare in manifest under
android:foregroundServiceType
mediaProcessing
- Permission to declare in your manifest
FOREGROUND_SERVICE_MEDIA_PROCESSING
- Constant to pass to
startForeground()
FOREGROUND_SERVICE_TYPE_MEDIA_PROCESSING
- Runtime prerequisites
- None
- Description
Service for performing time-consuming operations on media assets, like converting media to different formats. The system allows this service a limited time to run; under normal circumstances, this time limit would be 6 hours out of every 24. (This limit is shared by all of an app's
mediaProcessing
foreground services.)Your app should manually stop the media processing service in the following scenario:
- When the transcoding operation finishes or reaches a failure state, have the
service call
Service.stopForeground()
andService.stopSelf()
to stop the service completely.
- When the transcoding operation finishes or reaches a failure state, have the
service call
If the timeout period is reached, the system calls the service's
Service.onTimeout(int, int)
method. At this time, the service has a few seconds to callService.stopSelf()
. If the service does not callService.stopSelf()
, an ANR will occur with this error message: "A foreground service of <fgs_type> did not stop within its timeout: <component_name>".Note:
Service.onTimeout(int, int)
is not available on Android 14 or lower. On devices running those versions, if a media processing service reaches the timeout period, the system immediately caches the app. For this reason, your app shouldn't wait to get a timeout notification. Instead, it should terminate the foreground service or change it to a background service as soon as appropriate.
Projection multimédia
- Foreground service type to declare in manifest under
android:foregroundServiceType
mediaProjection
- Permission to declare in your manifest
FOREGROUND_SERVICE_MEDIA_PROJECTION
- Constant to pass to
startForeground()
FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION
- Runtime prerequisites
Call the
createScreenCaptureIntent()
method before starting the foreground service. Doing so shows a permission notification to the user; the user must grant the permission before you can create the service.After you have created the foreground service, you can call
MediaProjectionManager.getMediaProjection()
.- Description
Project content to non-primary display or external device using the
MediaProjection
APIs. This content doesn't have to be exclusively media content.- Alternatives
To stream media to another device, use the Google Cast SDK.
Micro
- Foreground service type to declare in manifest under
android:foregroundServiceType
microphone
- Permission to declare in your manifest
FOREGROUND_SERVICE_MICROPHONE
- Constant to pass to
startForeground()
FOREGROUND_SERVICE_TYPE_MICROPHONE
- Runtime prerequisites
Request and be granted the
RECORD_AUDIO
runtime permission.- Description
Continue microphone capture from the background, such as voice recorders or communication apps.
Appel téléphonique
- 要在清单中的以下位置声明的前台服务类型
android:foregroundServiceType
phoneCall
- 在清单中声明的权限
FOREGROUND_SERVICE_PHONE_CALL
- 要传递给
startForeground()
的常量 FOREGROUND_SERVICE_TYPE_PHONE_CALL
- 运行时前提条件
必须至少满足以下其中一个条件:
- 应用已在其清单文件中声明
MANAGE_OWN_CALLS
权限。
- 应用已在其清单文件中声明
- 应用是通过
ROLE_DIALER
角色的默认拨号器应用。
- 应用是通过
- 说明
使用
ConnectionService
API 继续当前通话。- 替代方案
如果您需要拨打电话、视频通话或 VoIP 通话,不妨考虑使用
android.telecom
库。考虑使用
CallScreeningService
来过滤来电。
Messagerie à distance
- Type de service de premier plan à déclarer dans le fichier manifeste sous
android:foregroundServiceType
remoteMessaging
- Autorisation de déclarer dans votre fichier manifeste
FOREGROUND_SERVICE_REMOTE_MESSAGING
- Constante à transmettre à
startForeground()
FOREGROUND_SERVICE_TYPE_REMOTE_MESSAGING
- Conditions requises pour l'environnement 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
- 要在其清单中声明的前台服务类型
android:foregroundServiceType
shortService
- 在清单中声明的权限
- 无
- 要传递给
startForeground()
的常量 FOREGROUND_SERVICE_TYPE_SHORT_SERVICE
- 运行时前提条件
- 无
- 说明
快速完成不可中断或推迟的关键工作。
这种类型有一些独特的特征:
- 只能持续运行一小段时间(大约 3 分钟)。
- 不支持粘性前台服务。
- 无法启动其他前台服务。
- 不需要类型专用权限,不过它仍需要
FOREGROUND_SERVICE
权限。 - 只有当应用当前有资格启动新的前台服务时,
shortService
才能更改为另一种服务类型。 - 前台服务可以随时将其类型更改为
shortService
,届时超时期限将开始。
shortService 的超时时间从调用
Service.startForeground()
开始算起。应用应在发生超时之前调用Service.stopSelf()
或Service.stopForeground()
。否则,系统会调用新的Service.onTimeout()
,让应用有机会调用stopSelf()
或stopForeground()
来停止其服务。调用
Service.onTimeout()
后的短时间内,应用会进入缓存状态,并且不再被视为处于前台,除非用户正在主动与应用互动。应用缓存一小段时间后,服务还未停止,该应用会收到 ANR 消息。ANR 消息提及FOREGROUND_SERVICE_TYPE_SHORT_SERVICE
。出于这些原因,实现Service.onTimeout()
回调被视为一种最佳实践。Android 13 及更低版本中不存在
Service.onTimeout()
回调。如果同一服务在此类设备上运行,则不会出现超时,也不会发生 ANR。确保您的服务在完成处理任务后立即停止,即使它尚未收到Service.onTimeout()
回调也是如此。请务必注意,如果未遵循
shortService
的超时设置,即使应用还有其他有效的前台服务或其他应用生命周期进程,应用也会遇到 ANR。如果应用对用户可见,或满足允许从后台启动前台服务的某一豁免条件,则使用
FOREGROUND_SERVICE_TYPE_SHORT_SERVICE
参数再次调用Service.StartForeground()
会将超时时间再延长 3 分钟。如果应用对用户不可见且不满足其中一个豁免条件,则尝试启动其他前台服务(无论其类型如何)都会导致ForegroundServiceStartNotAllowedException
。即使用户为您的应用停用电池优化功能,仍然会受到 shortService FGS 的影响。
如果您启动包含
shortService
类型和另一个前台服务类型的前台服务,系统会忽略shortService
类型声明。不过,该服务仍必须遵守其他声明类型的前提条件。如需了解详情,请参阅前台服务文档。
Utilisation spéciale
- Type de service de premier plan à déclarer dans le fichier manifeste sous
android:foregroundServiceType
specialUse
- Autorisation à déclarer dans votre fichier manifeste
FOREGROUND_SERVICE_SPECIAL_USE
- Constante à transmettre à
startForeground()
FOREGROUND_SERVICE_TYPE_SPECIAL_USE
- Conditions préalables à l'exécution
- Aucune
- Description
Recouvre les cas d'utilisation de services de premier plan valides qui ne sont pas couverts par les autres types de services de premier plan.
En plus de déclarer le type de service de premier plan
FOREGROUND_SERVICE_TYPE_SPECIAL_USE
, les développeurs doivent déclarer les cas d'utilisation dans le fichier manifeste. Pour ce faire, ils doivent spécifier l'élément<property>
dans l'élément<service>
. Ces valeurs et les cas d'utilisation correspondants sont examinés lorsque vous envoyez votre application dans la Google Play Console. L'utilisation des demandes que vous fournissez sont libres. Assurez-vous d'en fournir suffisamment des informations pour permettre à l'examinateur de savoir pourquoi vous devez utiliser l'specialUse
de mots clés.<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é
- Type de service de premier plan à déclarer dans le fichier manifeste sous
android:foregroundServiceType
systemExempted
- Autorisation de déclarer dans votre fichier manifeste
FOREGROUND_SERVICE_SYSTEM_EXEMPTED
- Constante à transmettre à
startForeground()
FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED
- Conditions requises pour l'environnement d'exécution
- Aucune
- Description
Réservé pour les applications système et les intégrations système spécifiques, afin de continuer à utiliser les services de premier plan.
Pour utiliser ce type, une application doit correspondre à au moins un des critères suivants :
- L'appareil est en mode démo
- L'application est un Device Owner
- L'application est un Profiler Owner
- Les applications de sécurité ayant le rôle
ROLE_EMERGENCY
- Les applications Device Admin
- Applications disposant de l'autorisation
SCHEDULE_EXACT_ALARM
ouUSE_EXACT_ALARM
Applications VPN (configurées sous Paramètres > Réseau et Internet > VPN)
Autrement, le fait de déclarer ce type renvoie une exception
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.