Os tipos de serviço em primeiro plano são obrigatórios

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:

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

Se os apps direcionados ao Android 14 usarem um serviço em primeiro plano, eles precisarão declarar uma permissão específica, com base no tipo de serviço em primeiro plano, que foi introduzida no Android 14. Essas permissões são exibidas nas seções denominadas "permissão que você precisa declarar no arquivo de manifesto" na seção de casos de uso pretendidos e aplicação de cada tipo de serviço em primeiro plano nesta página.

Todas as permissões são definidas como permissões normais e são concedidas por padrão. Os usuários não podem revogar essas permissões.

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

In order to use a given foreground service type, you must declare a particular permission in your manifest file, you must fulfill specific runtime requirements, and your app must fulfill one of the intended sets of use cases for that type. The following sections explain the permission that you must declare, the runtime prerequisites, and the intended use cases for each type.

Câmera

Tipo de serviço em primeiro plano a ser declarado no manifesto em android:foregroundServiceType
camera
Permissão a ser declarada no manifesto
FOREGROUND_SERVICE_CAMERA
Constante para transmitir para startForeground()
FOREGROUND_SERVICE_TYPE_CAMERA
Pré-requisitos do ambiente de execução

Solicitar e receber a permissão de execução CAMERA

Observação:a permissão de execução CAMERA está sujeita a restrições durante o uso. Por esse motivo, não é possível criar um serviço em primeiro plano camera enquanto o app está 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 em uso.

Descrição

Continue acessando a câmera em segundo plano, como em apps de chat por vídeo que permitem várias tarefas.

Dispositivo conectado

Tipo de serviço em primeiro plano a ser declarado no manifesto em
android:foregroundServiceType
connectedDevice
Permissão a ser declarada no manifesto
FOREGROUND_SERVICE_CONNECTED_DEVICE
Constante para transmitir para startForeground()
FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE
Pré-requisitos do ambiente de execução

Pelo menos uma das condições a seguir precisa ser verdadeira:

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 transferências de dados contínuas para um dispositivo externo, use o gerenciador de dispositivo complementar. Use a API de presença de dispositivo complementar para ajudar o app a continuar em execução enquanto o dispositivo complementar está no alcance.

Se o app precisar procurar dispositivos Bluetooth, use a API de verificação de Bluetooth.

Sincronização de dados

Tipo de serviço em primeiro plano a ser declarado no manifesto em
android:foregroundServiceType
dataSync
Permissão a ser declarada no manifesto
FOREGROUND_SERVICE_DATA_SYNC
Constante para transmitir para startForeground()
FOREGROUND_SERVICE_TYPE_DATA_SYNC
Pré-requisitos do ambiente 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 aos serviços em primeiro plano de sincronização de dados para informações detalhadas.

Saúde

Foreground service type to declare in manifest under
android:foregroundServiceType
health
Permission to declare in your manifest
FOREGROUND_SERVICE_HEALTH
Constant to pass to startForeground()
FOREGROUND_SERVICE_TYPE_HEALTH
Runtime prerequisites

At least one of the following conditions must be true:

Note: The BODY_SENSORS and sensor-based READ runtime permissions are subject to while-in-use restrictions. For this reason, you cannot create a health foreground service that uses body sensors while your app is in the background unless you've been granted the BODY_SENSORS_BACKGROUND (API level 33 to 35) or READ_HEALTH_DATA_IN_BACKGROUND (API level 36 and higher) permissions. For more information, see Restrictions on starting foreground services that need while-in-use permissions.

Description

Any long-running use cases to support apps in the fitness category such as exercise trackers.

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 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.

Mídia

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.

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 a microphone 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

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.

Mensagens remotas

Tipo de serviço em primeiro plano a ser declarado no manifesto em
android:foregroundServiceType
remoteMessaging
Permissão a ser declarada no manifesto
FOREGROUND_SERVICE_REMOTE_MESSAGING
Constante para transmitir para startForeground()
FOREGROUND_SERVICE_TYPE_REMOTE_MESSAGING
Pré-requisitos do ambiente 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 em
android:foregroundServiceType
shortService
Permissão a ser declarada no manifesto
Nenhum
Constante para transmitir para startForeground()
FOREGROUND_SERVICE_TYPE_SHORT_SERVICE
Pré-requisitos do ambiente 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ó pode 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 tipo para shortService a qualquer momento. Nesse ponto, o período de tempo limite começa.

O tempo limite de shortService começa no momento em que Service.startForeground() é chamado. O app precisa chamar Service.stopSelf() ou Service.stopForeground() antes que o tempo limite seja atingido. Caso contrário, o novo Service.onTimeout() será chamado, dando aos apps a oportunidade de chamar stopSelf() ou stopForeground() 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 menciona FOREGROUND_SERVICE_TYPE_SHORT_SERVICE. Por esses motivos, uma prática recomendada é implementar o callback Service.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 callback Service.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âmetro FOREGROUND_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 uma ForegroundServiceStartNotAllowedException.

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 tipo shortService. No entanto, o serviço ainda precisa aderir aos pré-requisitos dos outros tipos declarados. Para mais informações, consulte a documentação de serviços em primeiro plano.

Uso especial

Tipo de serviço em primeiro plano a ser declarado no manifesto em
android:foregroundServiceType
specialUse
Permissão a ser declarada no manifesto
FOREGROUND_SERVICE_SPECIAL_USE
Constante para transmitir para startForeground()
FOREGROUND_SERVICE_TYPE_SPECIAL_USE
Pré-requisitos do ambiente de execução
Nenhum
Descrição

Abrange todos os casos de uso de serviço em primeiro plano válidos que não são abrangidos por outros tipos de serviço em primeiro plano.

Além de declarar o tipo de serviço em primeiro plano FOREGROUND_SERVICE_TYPE_SPECIAL_USE, os desenvolvedores precisam declarar casos de uso no manifesto. Para fazer isso, especifique o elemento <property> no elemento <service>. Esses valores e os casos de uso correspondentes são analisados quando você envia o app no Google Play Console. Os casos de uso fornecidos são livres, e você precisa fornecer informações suficientes para que o revisor entenda por que você precisa usar o tipo specialUse.

<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

Tipo de serviço em primeiro plano a ser declarado no manifesto em
android:foregroundServiceType
systemExempted
Permissão a ser declarada no manifesto
FOREGROUND_SERVICE_SYSTEM_EXEMPTED
Constante para transmitir para startForeground()
FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED
Pré-requisitos do ambiente de execução
Nenhum
Descrição

Reservado para que aplicativos do sistema e integrações específicas do sistema possam continuar a usar serviços em primeiro plano.

Para usar esse tipo, um app precisa atender a pelo menos um destes critérios:

Aplicação da política do Google Play para uso de tipos de serviço em primeiro plano

Se o app for direcionado ao Android 14 ou versões mais recentes, será necessário declarar os tipos de serviço em primeiro plano na página "Conteúdo do app" do Play Console (Política > Conteúdo do app). Para mais informações sobre como declarar seus tipos de serviço em primeiro plano no Play Console, consulte Saiba mais sobre o serviço em primeiro plano e os requisitos de intent para tela cheia.