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 permissão
FOREGROUND_SERVICE). 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:foregroundServiceTypeconnectedDevice- 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:
Declare pelo menos uma das permissões a seguir no manifesto:
Solicitar e receber 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 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:foregroundServiceTypedataSync- Permissão a ser declarada no manifesto
FOREGROUND_SERVICE_DATA_SYNC- Constante para transmitir a
startForeground() FOREGROUND_SERVICE_TYPE_DATA_SYNC- Pré-requisitos de 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 de sincronização de dados em primeiro plano para informações detalhadas.
Saúde
- Foreground service type to declare in manifest under
android:foregroundServiceTypehealth- 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:
Declare the
HIGH_SAMPLING_RATE_SENSORSpermission in your manifest.Request and be granted at least one of the following runtime permissions:
BODY_SENSORSon API 35 and lowerREAD_HEART_RATEREAD_SKIN_TEMPERATUREREAD_OXYGEN_SATURATIONACTIVITY_RECOGNITION
- Description
Any long-running use cases to support apps in the fitness category such as exercise trackers.
Local
- Tipo de serviço em primeiro plano a ser declarado no manifesto em
android:foregroundServiceTypelocation- Permissão a ser declarada no manifesto
FOREGROUND_SERVICE_LOCATION- Constante para transmitir para
startForeground() FOREGROUND_SERVICE_TYPE_LOCATION- Pré-requisitos do ambiente de execução
O usuário precisa ter ativado os serviços de localização, e o app precisa ter pelo menos uma das seguintes permissões de execução:
- Descrição
Casos de uso de longa duração que exigem acesso à localização, como navegação e compartilhamento de local.
- Alternativas
Se o app precisar ser acionado quando o usuário chegar a locais específicos, use a API Geofence.
Mídia
- 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.
Mídia em processamento
- Foreground service type to declare in manifest under
android:foregroundServiceTypemediaProcessing- 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
mediaProcessingforeground services.)Your app should manually stop the media processing service in the following scenario:
- When the transcoding operation finishes or reaches a failure state, have the
service call
Service.stopForeground()andService.stopSelf()to stop the service completely.
- When the transcoding operation finishes or reaches a failure state, have the
service call
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 callService.stopSelf(). If the service does not callService.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
- 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.
Microfone
- 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.- 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:foregroundServiceTypephoneCall- 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 has declared the
MANAGE_OWN_CALLSpermission in its manifest file.
- App has declared the
- App is the default dialer app through the
ROLE_DIALERrole.
- App is the default dialer app through the
- Description
Continue an ongoing call using the
ConnectionServiceAPIs.- Alternatives
If you need to make phone, video, or VoIP calls, consider using the
android.telecomlibrary.Consider using
CallScreeningServiceto screen calls.
Mensagens remotas
- Foreground service type to declare in manifest under
android:foregroundServiceTyperemoteMessaging- 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:foregroundServiceTypeshortService- 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
shortServicesó 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
shortServicea 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 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
shortServicenã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
shortServicee outro tipo de serviço em primeiro plano, o sistema vai ignorar a declaração do tiposhortService. 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:foregroundServiceTypespecialUse- 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_USEforeground 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 thespecialUsetype.<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:foregroundServiceTypesystemExempted- 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_EMERGENCYrole - Device Admin apps
- Apps holding
SCHEDULE_EXACT_ALARMorUSE_EXACT_ALARMpermission 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.