To help developers be more intentional with defining user-facing foreground
services, Android 10 introduced the android:foregroundServiceType
attribute within the <service> element.
If your app targets Android 14, it must specify appropriate foreground service types. As in previous versions of Android, multiple types can be combined. This list shows the foreground service types to choose from:
cameraconnectedDevicedataSynchealthlocationmediaPlaybackmediaProjectionmicrophonephoneCallremoteMessagingshortServicespecialUsesystemExempted
If a use case in your app isn't associated with any of these types, we strongly recommend that you migrate your logic to use WorkManager or user-initiated data transfer jobs.
The health, remoteMessaging, shortService, specialUse, and systemExempted
types are new in Android 14.
The following code snippet provides an example of a foreground service type declaration in the manifest:
<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>
If an app that targets Android 14 doesn't define types for a given service in
the manifest, then the system will raise MissingForegroundServiceTypeException
upon calling startForeground() for that service.
Declara un nuevo permiso para usar tipos de servicio en primer plano
如果以 Android 14 为目标平台的应用使用前台服务,则必须根据前台服务类型声明 Android 14 中引入的特定权限。这些权限显示在本页每种前台服务类型的预期用例和强制执行部分中标记为“您必须在清单文件中声明的权限”的部分。
所有这些权限都定义为一般权限,并默认授予。用户无法撤消这些权限。
Incluye el tipo de servicio en primer plano durante el tiempo de ejecución
The best practice for applications starting foreground services is to use the
ServiceCompat version of startForeground() (available in androidx-core
1.12 and higher) where you pass in a bitwise
integer of foreground service types. You can choose to pass one or more type
values.
Usually, you should declare only the types required for a particular use case. This makes it easier to meet the system's expectations for each foreground service type. In cases where a foreground service is started with multiple types, then the foreground service must adhere to the platform enforcement requirements of all types.
ServiceCompat.startForeground(0, notification, FOREGROUND_SERVICE_TYPE_LOCATION)
If the foreground service type is not specified in the call, the type defaults
to the values defined in the manifest. If you didn't specify the service
type in the manifest, the system throws
MissingForegroundServiceTypeException.
If the foreground service needs new permissions after you launch it, you
should call startForeground() again and add the new service types. For
example, suppose a fitness app runs a running-tracker service that always needs
location information, but might or might not need media permissions. You
would need to declare both location and mediaPlayback in the manifest. If a
user starts a run and just wants their location tracked, your app should call
startForeground() and pass just the location service type. Then, if the user
wants to start playing audio, call startForeground() again and pass
location|mediaPlayback.
Verificaciones del tiempo de ejecución del sistema
系统会检查前台服务类型的使用是否恰当,并确认应用是否已请求适当的运行时权限或使用所需的 API。例如,系统希望使用前台服务类型 FOREGROUND_SERVICE_TYPE_LOCATION 的应用请求 ACCESS_COARSE_LOCATION 或 ACCESS_FINE_LOCATION。
这意味着,在向用户请求权限和启动前台服务时,应用必须遵循非常具体的操作顺序。应用在尝试调用 startForeground() 之前,必须先请求并获得所需的权限。在启动前台服务后请求相应权限的应用必须更改此顺序,并在启动前台服务之前请求该权限。
本页面的每种前台服务类型的预期用例和强制执行部分中标记为“运行时要求”的部分列出了平台强制执行的具体内容。
Casos de uso previstos y aplicación forzosa para cada tipo de servicio en primer plano
为了使用给定的前台服务类型,您必须在清单文件中声明特定权限,必须满足特定的运行时要求,并且应用必须满足该类型的其中一组预期用例。以下部分介绍了您必须声明的权限、运行时前提条件以及每种类型的预期用例。
Cámara
- Foreground service type to declare in manifest under
android:foregroundServiceType camera- Permission to declare in your manifest
FOREGROUND_SERVICE_CAMERA- Constant to pass to
startForeground() FOREGROUND_SERVICE_TYPE_CAMERA- Runtime prerequisites
Request and be granted the
CAMERAruntime permissionNote: The
CAMERAruntime permission is subject to while-in-use restrictions. For this reason, you cannot create acameraforeground service while your app is in the background, with a few exceptions. For more information, see Restrictions on starting foreground services that need while-in-use permissions.- Description
Continue to access the camera from the background, such as video chat apps that allow for multitasking.
Dispositivo conectado
- 要在清单中的以下位置声明的前台服务类型
android:foregroundServiceTypeconnectedDevice- 在清单中声明的权限
FOREGROUND_SERVICE_CONNECTED_DEVICE- 要传递给
startForeground()的常量 FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE- 运行时前提条件
必须至少满足以下其中一个条件:
在清单中至少声明以下其中一项权限:
至少请求并被授予以下其中一项运行时权限:
- 说明
与需要蓝牙、NFC、IR、USB 或网络连接的外部设备进行互动。
- 替代方案
如果您的应用需要向外部设备持续传输数据,请考虑改用配套设备管理器。使用配套设备感知 API,可帮助您的应用在配套设备在范围内时保持运行。
如果您的应用需要扫描蓝牙设备,请考虑改用 Bluetooth Scan API。
Sincronización de datos
- Tipo de servicio en primer plano que se declarará en el manifiesto en
android:foregroundServiceTypedataSync- Permiso para declarar en tu manifiesto
FOREGROUND_SERVICE_DATA_SYNC- Constante para pasar a
startForeground() FOREGROUND_SERVICE_TYPE_DATA_SYNC- Requisitos previos del entorno de ejecución
- Ninguno
- Descripción
Operaciones de transferencia de datos, como las siguientes:
- Sube o descarga de datos
- Operaciones de copia de seguridad y restablecimiento
- Operaciones de importación o exportación
- Cómo obtener datos
- Procesamiento de archivos locales
- Cómo transferir datos entre un dispositivo y la nube a través de una red
- Alternativas
Consulta Alternativas a los servicios en primer plano de sincronización de datos para obtener información detallada.
Salud
- Tipo de servicio en primer plano que se declarará en el manifiesto en
android:foregroundServiceTypehealth- Permiso para declarar en tu manifiesto
FOREGROUND_SERVICE_HEALTH- Es la constante que se pasa a
startForeground(). FOREGROUND_SERVICE_TYPE_HEALTH- Requisitos previos del entorno de ejecución
Debe cumplirse mínimo una de las siguientes condiciones:
Declara el permiso
HIGH_SAMPLING_RATE_SENSORSen tu manifiesto.Solicita y obtén al menos uno de los siguientes permisos de tiempo de ejecución:
BODY_SENSORSen el nivel de API 35 y versiones anterioresREAD_HEART_RATEREAD_SKIN_TEMPERATUREREAD_OXYGEN_SATURATIONACTIVITY_RECOGNITION
Nota: Los permisos de tiempo de ejecución de lectura
BODY_SENSORSy basados en sensores están sujetos a restricciones durante el uso. Por este motivo, no puedes crear un servicio en primer planohealthque use sensores corporales mientras tu app está en segundo plano, a menos que se te hayan otorgado los permisosBODY_SENSORS_BACKGROUND(nivel de API 33 a 35) oREAD_HEALTH_DATA_IN_BACKGROUND(nivel de API 36 y versiones posteriores). Para obtener más información, consulta Restringe el inicio de servicios en primer plano que necesiten permisos durante el uso.- Descripción
Cualquier caso de uso de larga duración para admitir apps de la categoría de entrenamiento, como monitoreos de ejercicios
Ubicación
- 要在清单中的以下位置声明的前台服务类型
android:foregroundServiceTypelocation- 在清单中声明的权限
FOREGROUND_SERVICE_LOCATION- 要传递给
startForeground()的常量 FOREGROUND_SERVICE_TYPE_LOCATION- 运行时前提条件
用户必须已启用位置信息服务,并且应用必须至少获得以下一项运行时权限:
注意:如需检查用户是否已启用位置信息服务以及是否已授予对运行时权限的访问权限,请使用
PermissionChecker#checkSelfPermission()注意:位置信息运行时权限受“使用期间”限制。因此,除非您已获得
ACCESS_BACKGROUND_LOCATION运行时权限,否则无法在应用在后台运行时创建location前台服务。如需了解详情,请参阅与启动需要“使用时”权限的前台服务相关的限制。- 说明
需要位置信息使用权的长时间运行的用例,例如导航和位置信息分享。
- 替代方案
如果您的应用需要在用户到达特定位置时触发,请考虑改用 Geofence API。
Contenido multimedia
- Foreground service type to declare in manifest under
android:foregroundServiceTypemediaPlayback- 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.
Proyección de contenido multimedia
- Foreground service type to declare in manifest under
android:foregroundServiceTypemediaProjection- 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
MediaProjectionAPIs. This content doesn't have to be exclusively media content.- Alternatives
To stream media to another device, use the Google Cast SDK.
Micrófono
- Foreground service type to declare in manifest under
android:foregroundServiceTypemicrophone- 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_AUDIOruntime permission.Note: The
RECORD_AUDIOruntime permission is subject to while-in-use restrictions. For this reason, you cannot create amicrophoneforeground service while your app is in the background, with a few exceptions. For more information, see Restrictions on starting foreground services that need while-in-use permissions.- Description
Continue microphone capture from the background, such as voice recorders or communication apps.
Llamada telefónica
- Tipo de servicio en primer plano que se declarará en el manifiesto en
android:foregroundServiceTypephoneCall- Permiso para declarar en tu manifiesto
FOREGROUND_SERVICE_PHONE_CALL- Constante para pasar a
startForeground() FOREGROUND_SERVICE_TYPE_PHONE_CALL- Requisitos previos del entorno de ejecución
Debe cumplirse al menos una de las siguientes condiciones:
- La app declaró el permiso
MANAGE_OWN_CALLSen su archivo de manifiesto.
- La app declaró el permiso
- La app es la app de teléfono predeterminada a través del rol
ROLE_DIALER.
- La app es la app de teléfono predeterminada a través del rol
- Descripción
Continúa una llamada en curso con las APIs de
ConnectionService.- Alternativas
Si necesitas hacer llamadas telefónicas, por video o por VoIP, considera usar la biblioteca
android.telecom.Considera usar
CallScreeningServicepara filtrar llamadas.
Mensajería remota
- Tipo de servicio en primer plano que se declarará en el manifiesto en
android:foregroundServiceTyperemoteMessaging- Permiso para declarar en tu manifiesto
FOREGROUND_SERVICE_REMOTE_MESSAGING- Constante para pasar a
startForeground() FOREGROUND_SERVICE_TYPE_REMOTE_MESSAGING- Requisitos previos del entorno de ejecución
- Ninguno
- Descripción
- Transfiere mensajes de texto de un dispositivo a otro. Brinda asistencia para la continuidad de las tareas de mensajería de un usuario cuando este cambia de dispositivo.
Servicio corto
- Foreground service type to declare in manifest under
android:foregroundServiceTypeshortService- 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_SERVICEpermission. - A
shortServicecan 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
shortServiceat 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 callService.stopSelf()orService.stopForeground()before the timeout occurs. Otherwise, the newService.onTimeout()is called, giving apps a brief opportunity to callstopSelf()orstopForeground()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 mentionsFOREGROUND_SERVICE_TYPE_SHORT_SERVICE. For these reasons, it's considered best practice to implement theService.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 theService.onTimeout()callback yet.It's important to note that if the timeout of the
shortServiceis 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 theFOREGROUND_SERVICE_TYPE_SHORT_SERVICEparameter 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 aForegroundServiceStartNotAllowedException.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
shortServicetype and another foreground service type, the system ignores theshortServicetype declaration. However, the service must still adhere to the prerequisites of the other declared types. For more information, see the Foreground services documentation.
Uso especial
- Tipo de servicio en primer plano que se declarará en el manifiesto en
android:foregroundServiceTypespecialUse- Permiso para declarar en tu manifiesto
FOREGROUND_SERVICE_SPECIAL_USE- Constante para pasar a
startForeground() FOREGROUND_SERVICE_TYPE_SPECIAL_USE- Requisitos previos del entorno de ejecución
- Ninguno
- Descripción
Abarca todos los casos de uso válidos de servicios en primer plano que no están cubiertos por los otros tipos de servicios en primer plano.
Además de declarar el tipo de servicio en primer plano de
FOREGROUND_SERVICE_TYPE_SPECIAL_USE, los desarrolladores deben declarar casos de uso en el manifiesto. Para ello, especifican el elemento<property>dentro del objeto<service>. Estos valores y los casos de uso correspondientes se revisan cuando envías tu app en Google Play Console. El uso son de formato libre, y debes asegurarte de proporcionar suficientes información para que el revisor pueda ver por qué necesitas usarspecialUseel tipo de letra.<service android:name="fooService" android:foregroundServiceType="specialUse"> <property android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE" android:value="explanation_for_special_use"/> </service>
Sistema exento
- Tipo de servicio en primer plano que se declarará en el manifiesto en
android:foregroundServiceTypesystemExempted- Permiso para declarar en tu manifiesto
FOREGROUND_SERVICE_SYSTEM_EXEMPTED- Constante para pasar a
startForeground() FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED- Requisitos previos del entorno de ejecución
- Ninguno
- Descripción
Reservado para aplicaciones del sistema y integraciones de sistemas específicos, para continuar usando los servicios en primer plano.
Para usar este tipo, una app debe cumplir con mínimo uno de los siguientes criterios:
- El dispositivo debe estar en modo de demostración
- La app debe ser del propietario del dispositivo
- La app debe ser del propietario del generador de perfiles.
- Apps de seguridad que tienen la función
ROLE_EMERGENCY - Apps de administración del dispositivo
- Apps que tienen el permiso
SCHEDULE_EXACT_ALARMoUSE_EXACT_ALARMy usan el servicio en primer plano para continuar con las alarmas en segundo plano, incluidas las alarmas solo táctiles Apps de VPN (configuradas con Configuración > Internet y redes > VPN)
De lo contrario, declarar este tipo causa que el sistema arroje una
ForegroundServiceTypeNotAllowedException.
Aplicación forzosa de las políticas de Google Play para usar tipos de servicios en primer plano
Si tu app se segmenta para Android 14 o versiones posteriores, deberás declarar los tipos de servicios en primer plano de la app en la página Contenido de la app de Play Console (Política > Contenido de la app). Para obtener más información sobre cómo declarar los tipos de servicios en primer plano en Play Console, consulta Información sobre los requisitos de los intents de pantalla completa y los servicios en primer plano.