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

为了帮助开发者更有目的地定义面向用户的前台服务,Android 10 在 <service> 元素内引入了 android:foregroundServiceType 属性。

如果您的应用以 Android 14 为目标平台,则必须指定适当的前台服务类型。与以前的 Android 版本一样,可组合使用多个类型。下面列出了可供选择的前台服务类型:

如果应用中的用例与这些类型均不相关,强烈建议您迁移逻辑以使用 WorkManager用户发起的数据传输作业

Android 14 中新增了 health, remoteMessaging, shortService, specialUsesystemExempted 类型。

以下代码段提供了一个清单中的前台服务类型声明示例:

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

如果以 Android 14 为目标平台的应用未在清单中定义给定服务的类型,系统会在调用 startForeground() 时引发 MissingForegroundServiceTypeException

Declarar nova permissão para usar tipos de serviço em primeiro plano

如果以 Android 14 为目标平台的应用使用前台服务,则必须根据前台服务类型声明 Android 14 中引入的特定权限。这些权限显示在本页每种前台服务类型的预期用例和强制执行部分中标记为“您必须在清单文件中声明的权限”的部分。

所有这些权限都定义为一般权限,并默认授予。用户无法撤消这些权限。

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

系统会检查前台服务类型的使用是否恰当,并确认应用是否已请求适当的运行时权限或使用所需的 API。例如,系统希望使用前台服务类型 FOREGROUND_SERVICE_TYPE_LOCATION 的应用请求 ACCESS_COARSE_LOCATIONACCESS_FINE_LOCATION

这意味着,在向用户请求权限和启动前台服务时,应用必须遵循非常具体的操作顺序。应用在尝试调用 startForeground() 之前,必须先请求并获得所需的权限。在启动前台服务后请求相应权限的应用必须更改此顺序,并在启动前台服务之前请求该权限。

本页面的每种前台服务类型的预期用例和强制执行部分中标记为“运行时要求”的部分列出了平台强制执行的具体内容。

Casos de uso pretendidos e aplicação de cada tipo de serviço em primeiro plano

为了使用给定的前台服务类型,您必须在清单文件中声明特定权限,必须满足特定的运行时要求,并且应用必须满足该类型的其中一组预期用例。以下部分介绍了您必须声明的权限、运行时前提条件以及每种类型的预期用例。

Câmera

要在 android:foregroundServiceType 下在清单中声明的前台服务类型
camera
在清单中声明的权限
FOREGROUND_SERVICE_CAMERA
要传递给 startForeground() 的常量
FOREGROUND_SERVICE_TYPE_CAMERA
运行时前提条件

请求并获得 CAMERA 运行时权限

注意CAMERA 运行时权限受使用时限制的约束。因此,除少数例外情况外,您无法在应用在后台运行时创建 camera 前台服务。如需了解详情,请参阅与启动需要“使用时”权限的前台服务相关的限制

说明

继续在后台访问相机,例如支持多任务的视频聊天应用。

Dispositivo conectado

要在清单中的以下位置声明的前台服务类型
android:foregroundServiceType
connectedDevice
在清单中声明的权限
FOREGROUND_SERVICE_CONNECTED_DEVICE
要传递给 startForeground() 的常量
FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE
运行时前提条件

必须至少满足以下其中一个条件:

说明

与需要蓝牙、NFC、IR、USB 或网络连接的外部设备进行互动。

替代方案

如果您的应用需要向外部设备持续传输数据,请考虑改用配套设备管理器。使用配套设备感知 API,可帮助您的应用在配套设备在范围内时保持运行。

如果您的应用需要扫描蓝牙设备,请考虑改用 Bluetooth Scan API

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:

Note: The BODY_SENSORS runtime permission is 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, with a few exceptions. 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

要在清单中的以下位置声明的前台服务类型
android:foregroundServiceType
location
在清单中声明的权限
FOREGROUND_SERVICE_LOCATION
要传递给 startForeground() 的常量
FOREGROUND_SERVICE_TYPE_LOCATION
运行时前提条件

用户必须已启用位置信息服务,并且应用必须至少获得以下一项运行时权限:

注意:如需检查用户是否已启用位置信息服务以及是否已授予对运行时权限的访问权限,请使用 PermissionChecker#checkSelfPermission()

注意:位置信息运行时权限受“使用期间”限制。因此,除非您已获得 ACCESS_BACKGROUND_LOCATION 运行时权限,否则无法在应用在后台运行时创建 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

要在清单中的以下位置声明的前台服务类型
android:foregroundServiceType
mediaProjection
在清单中声明的权限
FOREGROUND_SERVICE_MEDIA_PROJECTION
要传递给 startForeground() 的常量
FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION
运行时前提条件

在启动前台服务之前调用 createScreenCaptureIntent() 方法。这样做会向用户显示权限通知;用户必须先授予权限,您才能创建服务。

创建前台服务后,您可以调用 MediaProjectionManager.getMediaProjection()

说明

使用 MediaProjection API 将内容投影到非主要显示屏或外部设备。这些内容不必全都为媒体内容。

替代方案

如需将媒体流式传输到其他设备,请使用 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

要在清单中的以下位置声明的前台服务类型
android:foregroundServiceType
phoneCall
在清单中声明的权限
FOREGROUND_SERVICE_PHONE_CALL
要传递给 startForeground() 的常量
FOREGROUND_SERVICE_TYPE_PHONE_CALL
运行时前提条件

必须至少满足以下其中一个条件:

  • 应用是通过 ROLE_DIALER 角色的默认拨号器应用。
说明

使用 ConnectionService API 继续当前通话。

替代方案

如果您需要拨打电话、视频通话或 VoIP 通话,不妨考虑使用 android.telecom 库。

考虑使用 CallScreeningService 来过滤来电。

Mensagens remotas

要在清单中的以下位置声明的前台服务类型
android:foregroundServiceType
remoteMessaging
在清单中声明的权限
FOREGROUND_SERVICE_REMOTE_MESSAGING
要传递给 startForeground() 的常量
FOREGROUND_SERVICE_TYPE_REMOTE_MESSAGING
运行时前提条件
说明
将短信从一台设备转移到另一台设备。在用户切换设备时,帮助确保用户消息任务的连续性。

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

要在清单中声明的前台服务类型
android:foregroundServiceType
specialUse
在清单中声明的权限
FOREGROUND_SERVICE_SPECIAL_USE
要传递给 startForeground() 的常量
FOREGROUND_SERVICE_TYPE_SPECIAL_USE
运行时前提条件
说明

涵盖其他前台服务类型未涵盖的所有有效前台服务用例。

除了声明 FOREGROUND_SERVICE_TYPE_SPECIAL_USE 前台服务类型之外,开发者还应在清单中声明用例。为此,他们会在 <service> 元素内指定 <property> 元素。这些值和相应的应用场景 。用途 您提供的案例均为自由形式,因此,您应确保提供足够的 相关信息,让审核人员了解您为何需要使用 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

要在清单中的以下位置声明的前台服务类型
android:foregroundServiceType
systemExempted
在清单中声明的权限
FOREGROUND_SERVICE_SYSTEM_EXEMPTED
要传递给 startForeground() 的常量
FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED
运行时前提条件
说明

为系统应用和特定系统集成预留,使其能继续使用前台服务。

如需使用此类型,应用必须至少满足以下条件之一:

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.