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

Para ajudar os desenvolvedores na definição de serviços em primeiro plano voltados ao usuário, o Android 10 introduziu o atributo android:foregroundServiceType no elemento <service>.

Caso o app seja destinado ao Android 14, é necessário especificar os tipos de serviço em primeiro plano adequados. Como nas versões anteriores do Android, vários tipos podem ser combinados. Esta lista mostra os tipos de serviço em primeiro plano que você pode escolher:

Se um caso de uso no app não estiver associado a nenhum desses tipos, é recomendável migrar a lógica para usar o WorkManager ou jobs de transferência de dados iniciados pelo usuário.

Os tipos health, remoteMessaging, shortService, specialUse e systemExempted são novos no Android 14.

O snippet de código abaixo mostra um exemplo de declaração de tipo de serviço em primeiro plano no manifesto:

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

Se um app destinado ao Android 14 não definir tipos para um determinado serviço no manifesto, o sistema vai gerar uma MissingForegroundServiceTypeException ao chamar startForeground() para o serviço.

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

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

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 permission

Note: The CAMERA runtime permission is subject to while-in-use restrictions. For this reason, you cannot create a camera 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

Foreground service type to declare in manifest under
android:foregroundServiceType
connectedDevice
Permission to declare in your manifest
FOREGROUND_SERVICE_CONNECTED_DEVICE
Constant to pass to startForeground()
FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE
Runtime prerequisites

At least one of the following conditions must be true:

Description

Interactions with external devices that require a Bluetooth, NFC, IR, USB, or network connection.

Alternatives

If your app needs to do continuous data transfer to an external device, consider using the companion device manager instead. Use the companion device presence API to help your app stay running while the companion device is in range.

If your app needs to scan for bluetooth devices, consider using the Bluetooth scan API instead.

Sincronização de dados

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.

Saúde

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

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

Observação:as permissões de leitura de BODY_SENSORS e baseadas em sensores estão sujeitas a restrições durante o uso. Por esse motivo, não é possível criar um serviço em primeiro plano health que use sensores corporais enquanto o app está em segundo plano, a menos que você tenha recebido as permissões BODY_SENSORS_BACKGROUND (nível 33 a 35 da API) ou READ_HEALTH_DATA_IN_BACKGROUND (nível 36 e mais recente da API). Para mais informações, consulte Restrições para iniciar serviços em primeiro plano que precisam de permissões em 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 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

Tipo de serviço em primeiro plano a ser declarado no manifesto em
android:foregroundServiceType
mediaPlayback
Permissão a ser declarada no manifesto
FOREGROUND_SERVICE_MEDIA_PLAYBACK
Constante para transmitir para startForeground()
FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK
Pré-requisitos do ambiente 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 mostrando um vídeo 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 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

Foreground service type to declare in manifest under
android:foregroundServiceType
remoteMessaging
Permission to declare in your manifest
FOREGROUND_SERVICE_REMOTE_MESSAGING
Constant to pass to startForeground()
FOREGROUND_SERVICE_TYPE_REMOTE_MESSAGING
Runtime prerequisites
None
Description
Transfer text messages from one device to another. Assists with continuity of a user's messaging tasks when they switch devices.

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

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>

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

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.