No Android 14 (nível 34 da API) e versões mais recentes, é 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 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
- 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
- 要在清单中声明的前台服务类型
android:foregroundServiceType
location
- 在清单中声明的权限
FOREGROUND_SERVICE_LOCATION
- 要传递给
startForeground()
的常量 FOREGROUND_SERVICE_TYPE_LOCATION
- 运行时前提条件
用户必须已启用位置信息服务,并且必须至少向应用授予以下运行时权限之一:
注意:如需检查用户是否已启用位置信息服务以及是否已授予运行时权限的访问权限,请使用
PermissionChecker#checkSelfPermission()
注意:位置信息运行时权限受使用时限制的约束。因此,当应用在后台运行时,您无法创建
location
前台服务,除非您已被授予ACCESS_BACKGROUND_LOCATION
运行时权限。如需了解详情,请参阅对启动需要在使用时授予权限的前台服务的限制。- 说明
需要位置信息使用权的长时间运行的用例,例如导航和位置信息分享。
- 替代方案
如果您的应用需要在用户到达特定位置时触发,请考虑改用 Geofence API。
Mídia
- 要在其清单中声明的前台服务类型
android:foregroundServiceType
mediaPlayback
- 在清单中声明的权限
FOREGROUND_SERVICE_MEDIA_PLAYBACK
- 要传递给
startForeground()
的常量 FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK
- 运行时前提条件
- 无
- 说明
- 在后台继续播放音频或视频。在 Android TV 上支持数字视频录制 (DVR) 功能。
- 替代方案
- 如果您显示的是画中画视频,请使用画中画模式。
Projeção de mídia
- Tipo de serviço em primeiro plano a ser declarado no manifesto
android:foregroundServiceType
mediaProjection
- Permissão a ser declarada no manifesto
FOREGROUND_SERVICE_MEDIA_PROJECTION
- Constante a ser transmitida para
startForeground()
FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION
- Pré-requisitos de tempo 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 concedê-la antes de você 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 em outro dispositivo, use o SDK do Google Cast.
Microfone
- Tipo de serviço em primeiro plano a ser declarado no manifesto
android:foregroundServiceType
microphone
- Permissão a ser declarada no manifesto
FOREGROUND_SERVICE_MICROPHONE
- Constante a ser transmitida para
startForeground()
FOREGROUND_SERVICE_TYPE_MICROPHONE
- Pré-requisitos de tempo de execução
Solicite e receba a permissão de execução
RECORD_AUDIO
.Observação:a permissão de execução
RECORD_AUDIO
está sujeita a restrições durante o uso. Por esse motivo, não é possível criar um serviço em primeiro planomicrophone
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 durante o uso.- Descrição
Continue a captura do microfone em segundo plano, como gravadores de voz ou apps de comunicação.
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
- 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
- Foreground service type to declare in manifest under
android:foregroundServiceType
shortService
- Permission to declare in your manifest
- None
- Constant to pass to
startForeground()
FOREGROUND_SERVICE_TYPE_SHORT_SERVICE
- Runtime prerequisites
- None
- Description
Quickly finish critical work that cannot be interrupted or postponed.
This type has some unique characteristics:
- Can only run for a short period of time (about 3 minutes).
- No support for sticky foreground services.
- Cannot start other foreground services.
- Doesn't require a type-specific permission, though it still
requires the
FOREGROUND_SERVICE
permission. - A
shortService
can only change to another service type if the app is currently eligible to start a new foreground service. - A foreground service can change its type to
shortService
at any time, at which point the timeout period begins.
The timeout for shortService begins from the moment that
Service.startForeground()
is called. The app is expected to callService.stopSelf()
orService.stopForeground()
before the timeout occurs. Otherwise, the newService.onTimeout()
is called, giving apps a brief opportunity to callstopSelf()
orstopForeground()
to stop their service.A short time after
Service.onTimeout()
is called, the app enters a cached state and is no longer considered to be in the foreground, unless the user is actively interacting with the app. A short time after the app is cached and the service has not stopped, the app receives an ANR. The ANR message mentionsFOREGROUND_SERVICE_TYPE_SHORT_SERVICE
. For these reasons, it's considered best practice to implement theService.onTimeout()
callback.The
Service.onTimeout()
callback doesn't exist on Android 13 and lower. If the same service runs on such devices, it doesn't receive a timeout, nor does it ANR. Make sure that your service stops as soon as it finishes the processing task, even if it hasn't received theService.onTimeout()
callback yet.It's important to note that if the timeout of the
shortService
is not respected, the app will ANR even if it has other valid foreground services or other app lifecycle processes running.If an app is visible to the user or satisfies one of the exemptions that allow foreground services to be started from the background, calling
Service.StartForeground()
again with theFOREGROUND_SERVICE_TYPE_SHORT_SERVICE
parameter extends the timeout by another 3 minutes. If the app isn't visible to the user and doesn't satisfy one of the exemptions, any attempt to start another foreground service, regardless of type, causes aForegroundServiceStartNotAllowedException
.If a user disables battery optimization for your app, it's still affected by the timeout of shortService FGS.
If you start a foreground service that includes the
shortService
type and another foreground service type, the system ignores theshortService
type declaration. However, the service must still adhere to the prerequisites of the other declared types. For more information, see the Foreground services documentation.
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
- 要在清单中声明的前台服务类型
android:foregroundServiceType
systemExempted
- 在清单中声明的权限
FOREGROUND_SERVICE_SYSTEM_EXEMPTED
- 要传递给
startForeground()
的常量 FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED
- 运行时前提条件
- 无
- 说明
为系统应用和特定系统集成预留, 继续使用前台服务。
如需使用此类型,应用必须至少满足以下条件之一:
- 设备处于演示模式状态
- 应用是设备所有者
- 应用是性能分析器所有者
- 属于具有
ROLE_EMERGENCY
角色的安全应用 - 属于设备管理应用
- 持有
SCHEDULE_EXACT_ALARM
或USE_EXACT_ALARM
权限,并且正在使用 前台服务用于在后台继续闹钟, 包括仅触感反馈闹钟。 VPN 应用(通过设置 > 网络和互联网 > VPN 配置)
否则,声明此类型会导致系统抛出
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.