Tipos de serviços em primeiro plano

A partir do Android 14 (nível 34 da API), é necessário declarar um tipo de serviço adequado para cada serviço em primeiro plano. Isso significa que você precisa declarar o tipo de serviço no manifesto do app e também solicitar a permissão de serviço em primeiro plano adequada para esse tipo (além de solicitar a FOREGROUND_SERVICE permissão). Além disso, dependendo do tipo de serviço em primeiro plano, talvez seja necessário solicitar permissões de execução antes de iniciar o serviço.

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 a startForeground()
FOREGROUND_SERVICE_TYPE_CAMERA
Pré-requisitos de ambiente de execução

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

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

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

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:

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:

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.

Mídia em processamento

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:

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 call Service.stopSelf(). If the service does not call Service.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.

Projeção de mídia

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

Chame o método createScreenCaptureIntent() antes de iniciar o serviço em primeiro plano. Isso mostra uma notificação de permissão ao usuário, que precisa conceder a permissão antes que você possa criar o serviço.

Depois de criar o serviço em primeiro plano, chame MediaProjectionManager.getMediaProjection().

Descrição

Projete o conteúdo em uma tela secundária ou um dispositivo externo usando as APIs MediaProjection. Esse conteúdo não precisa ser exclusivamente de mídia.

Alternativas

Para fazer streaming de mídia para outro dispositivo, use o SDK do Google Cast.

Microfone

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

Solicite e receba a permissão de execução RECORD_AUDIO.

Descrição

Continue a captura do microfone em segundo plano com, por exemplo, gravadores de voz ou apps de comunicação.

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

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:

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

If your app targets Android 14 or higher, you'll need to declare your app's foreground service types in the Play Console's app content page (Policy > App content). For more information on how to declare your foreground service types in Play Console, see Understanding foreground service and full-screen intent requirements.