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:
camera
connectedDevice
dataSync
health
location
mediaPlayback
mediaProjection
microphone
phoneCall
remoteMessaging
shortService
specialUse
systemExempted
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.
Declarar nova permissão para usar tipos de serviço em primeiro plano
If apps that target Android 14 use a foreground service, they must declare a specific permission, based on the foreground service type, that Android 14 introduces. These permissions appear in the sections labeled "permission that you must declare in your manifest file" in the intended use cases and enforcement for each foreground service type section on this page.
All of the permissions are defined as normal permissions and are granted by default. Users cannot revoke these permissions.
Incluir tipo de serviço em primeiro plano no momento da execução
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
.
Verificações do momento de execução no sistema
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.
Casos de uso pretendidos e aplicação de cada tipo de serviço em primeiro plano
Para usar determinado tipo de serviço em primeiro plano, é necessário declarar uma permissão específica no arquivo de manifesto e atender a requisitos de execução específicos. Além disso, seu app precisa atender a um dos conjuntos de casos de uso pretendidos para esse tipo. As seções a seguir explicam a permissão que você precisa declarar, os pré-requisitos de execução e os casos de uso pretendidos para cada tipo.
Câmera
- 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
CAMERA
runtime permissionNote: The
CAMERA
runtime permission is subject to while-in-use restrictions. For this reason, you cannot create acamera
foreground 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
- Tipo de serviço em primeiro plano a ser declarado no manifesto
android:foregroundServiceType
connectedDevice
- Permissão a ser declarada no manifesto
FOREGROUND_SERVICE_CONNECTED_DEVICE
- Constante a ser transmitida para
startForeground()
FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE
- Pré-requisitos de tempo de execução
Pelo menos uma das condições a seguir precisa ser verdadeira:
Declare pelo menos uma das permissões a seguir no manifesto:
Solicite e receba pelo menos uma das seguintes permissões de execução:
- Descrição
Interações com dispositivos externos que exigem uma conexão Bluetooth, NFC, IR, USB ou de rede.
- Alternativas
Se o app precisar fazer uma transferência contínua de dados para um dispositivo externo, use o gerenciador de dispositivos complementar. Use a API de presença de dispositivo complementar para ajudar o app a continuar em execução enquanto o dispositivo complementar estiver ao alcance.
Se o app precisar procurar dispositivos Bluetooth, use a API Bluetooth Scan.
Sincronização de dados
- Tipo de serviço em primeiro plano a ser declarado no manifesto
android:foregroundServiceType
dataSync
- Permissão a ser declarada no manifesto
FOREGROUND_SERVICE_DATA_SYNC
- Constante a ser transmitida para
startForeground()
FOREGROUND_SERVICE_TYPE_DATA_SYNC
- Pré-requisitos de tempo de execução
- Nenhum
- Descrição
Operações de transferência de dados, como as seguintes:
- Upload ou download de dados
- Operações de backup e restauração
- Operações de importação ou exportação
- Busca de dados
- Processamento local de arquivos
- Transferência de dados entre um dispositivo e a nuvem por uma rede
- Alternativas
Consulte Alternativas à sincronização de dados para serviços em primeiro plano para informações detalhadas.
Saúde
- Tipo de serviço em primeiro plano a ser declarado no manifesto
android:foregroundServiceType
health
- Permissão a ser declarada no manifesto
FOREGROUND_SERVICE_HEALTH
- Constante a ser transmitida para
startForeground()
FOREGROUND_SERVICE_TYPE_HEALTH
- Pré-requisitos de tempo de execução
Pelo menos uma das condições a seguir precisa ser verdadeira:
Declare a permissão
HIGH_SAMPLING_RATE_SENSORS
no manifesto.Solicite e receba pelo menos uma das seguintes permissões de execução:
Observação:a permissão de execução
BODY_SENSORS
está sujeita a restrições durante o uso. Por esse motivo, não é possível criar um serviço em primeiro planohealth
que use sensores corporais enquanto o app estiver em segundo plano, com algumas exceções. Para mais informações, consulte Restrições para iniciar serviços em primeiro plano que precisam de permissões durante o uso.- Descrição
Todos os casos de uso de longa duração que oferecem suporte a apps na categoria fitness, como apps de monitoramento de atividade física.
Local
- 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 theACCESS_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.
Mídia
- Tipo de serviço em primeiro plano a ser declarado no manifesto
android:foregroundServiceType
mediaPlayback
- Permissão a ser declarada no manifesto
FOREGROUND_SERVICE_MEDIA_PLAYBACK
- Constante a ser transmitida para
startForeground()
FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK
- Pré-requisitos de tempo de execução
- Nenhum
- Descrição
- Continue reproduzindo áudio ou vídeo em segundo plano. Suporte à funcionalidade de gravação de vídeo digital (DVR) no Android TV.
- Alternativas
- Se você estiver exibindo vídeos picture-in-picture, use o modo picture-in-picture.
Projeção de mí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.
Microfone
- 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.Note: The
RECORD_AUDIO
runtime permission is subject to while-in-use restrictions. For this reason, you cannot create amicrophone
foreground 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.
Ligação telefônica
- Tipo de serviço em primeiro plano a ser declarado no manifesto
android:foregroundServiceType
phoneCall
- Permissão a ser declarada no manifesto
FOREGROUND_SERVICE_PHONE_CALL
- Constante a ser transmitida para
startForeground()
FOREGROUND_SERVICE_TYPE_PHONE_CALL
- Pré-requisitos de tempo de execução
Pelo menos uma destas condições precisa ser verdadeira:
- O app declarou a permissão
MANAGE_OWN_CALLS
no arquivo de manifesto.
- O app declarou a permissão
- Esse é o app de discador padrão com o papel
ROLE_DIALER
.
- Esse é o app de discador padrão com o papel
- Descrição
Continue uma chamada usando as APIs
ConnectionService
.- Alternativas
Se você precisar fazer chamadas telefônicas, de vídeo ou VoIP, considere usar a biblioteca
android.telecom
.Use o
CallScreeningService
para filtrar ligações.
Mensagens remotas
- Tipo de serviço em primeiro plano a ser declarado no manifesto
android:foregroundServiceType
remoteMessaging
- Permissão a ser declarada no manifesto
FOREGROUND_SERVICE_REMOTE_MESSAGING
- Constante a ser transmitida para
startForeground()
FOREGROUND_SERVICE_TYPE_REMOTE_MESSAGING
- Pré-requisitos de tempo de execução
- Nenhum
- Descrição
- Transferir mensagens de texto de um dispositivo para outro. Ajuda na continuidade das tarefas de mensagens de um usuário ao trocar de dispositivo.
Serviço curto
- Tipo de serviço em primeiro plano a ser declarado no manifesto
android:foregroundServiceType
shortService
- Permissão a ser declarada no manifesto
- Nenhum
- Constante a ser transmitida para
startForeground()
FOREGROUND_SERVICE_TYPE_SHORT_SERVICE
- Pré-requisitos de tempo de execução
- Nenhum
- Descrição
Conclua rapidamente trabalhos essenciais que não podem ser interrompidos ou adiados.
Esse tipo tem algumas características únicas:
- Pode ser executado por um curto período de tempo (cerca de três minutos).
- Não oferece suporte a serviços fixos em primeiro plano.
- Não inicia outros serviços em primeiro plano.
- Não requer uma permissão específica do tipo, embora ainda
exija a permissão
FOREGROUND_SERVICE
. - Um
shortService
só poderá mudar para outro tipo de serviço se o app estiver qualificado para iniciar um novo serviço em primeiro plano. - Um serviço em primeiro plano pode mudar o próprio tipo para
shortService
a qualquer momento, quando o tempo limite começa.
O tempo limite de shortService começa no momento em que
Service.startForeground()
é chamado. O app precisa chamarService.stopSelf()
ouService.stopForeground()
antes que o tempo limite seja atingido. Caso contrário, o novoService.onTimeout()
será chamado, dando aos apps a oportunidade de chamarstopSelf()
oustopForeground()
para interromper o serviço.Pouco depois que
Service.onTimeout()
é chamado, o app entra em um estado em cache e não é mais considerado em primeiro plano, a menos que o usuário esteja interagindo ativamente com ele. Se o app entra nesse estado e o serviço não é interrompido, o app recebe um erro ANR. A mensagem ANR mencionaFOREGROUND_SERVICE_TYPE_SHORT_SERVICE
. Por esses motivos, uma prática recomendada é implementar o callbackService.onTimeout()
.O callback
Service.onTimeout()
não existe no Android 13 e nas versões anteriores. Se o mesmo serviço for executado nesses dispositivos, ele não receberá um tempo limite nem um erro ANR. Confira se o serviço é interrompido assim que a tarefa de processamento é terminada, mesmo que ele ainda não tenha recebido o callbackService.onTimeout()
.É importante observar que, se o tempo limite do
shortService
não for respeitado, o app receberá um erro ANR mesmo que tenha outros serviços em primeiro plano válidos ou outros processos de ciclo de vida em execução.Se um app estiver visível para o usuário ou atender a uma das isenções que permitem que serviços em primeiro plano sejam iniciados em segundo plano, chame
Service.StartForeground()
novamente com o parâmetroFOREGROUND_SERVICE_TYPE_SHORT_SERVICE
, que estende o tempo limite em mais três minutos. Se o app não estiver visível para o usuário e não atender a uma das isenções, qualquer tentativa de iniciar outro serviço em primeiro plano, independente do tipo, vai causar umaForegroundServiceStartNotAllowedException
.Se um usuário desativar a otimização da bateria para seu app, ele ainda será afetado pelo tempo limite do shortService FGS.
Se você iniciar um serviço em primeiro plano que inclua o tipo
shortService
e outro tipo de serviço em primeiro plano, o sistema vai ignorar a declaração do tiposhortService
. No entanto, o serviço ainda precisará aderir aos pré-requisitos dos outros tipos declarados. Para mais informações, consulte a documentação de serviços em primeiro plano.
Uso especial
- 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 thespecialUse
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>
Sistema isento
- 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
orUSE_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
.
Aplicação da política do Google Play para uso de tipos de serviço em primeiro plano
Caso o app seja destinado ao Android 14 ou versões mais recentes, declare os tipos de serviço em primeiro plano na página de conteúdo do app no Play Console (Política > Conteúdo do app). Para mais informações sobre como declarar os tipos de serviço em primeiro plano no Play Console, consulte Noções básicas sobre o serviço em primeiro plano e os requisitos de intent para tela cheia.