I tipi di servizi in primo piano sono obbligatori

为了帮助开发者更有目的地定义面向用户的前台服务,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

Dichiara la nuova autorizzazione per utilizzare i tipi di servizi in primo piano

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.

Includi il tipo di servizio in primo piano in fase di esecuzione

对于启动前台服务的应用,最佳实践是使用 startForeground()ServiceCompat 版本(在 androidx-core 1.12 及更高版本中提供),并在其中传入前台服务类型的按位整数。您可以选择传递一个或多个类型值。

通常,您应仅声明特定用例所需的类型。这样可以更轻松地满足系统对每种前台服务类型的预期。如果某项前台服务以多种类型启动,则该前台服务必须遵守所有类型的平台强制执行要求

ServiceCompat.startForeground(0, notification, FOREGROUND_SERVICE_TYPE_LOCATION)

如果在调用中未指定前台服务类型,则类型默认为清单中定义的值。如果您未在清单中指定服务类型,系统会抛出 MissingForegroundServiceTypeException

如果前台服务在启动后需要新权限,您应再次调用 startForeground() 并添加新的服务类型。例如,假设一款健身应用运行一项始终需要 location 信息但可能不需要 media 权限的跑步跟踪器服务。您需要在清单中同时声明 locationmediaPlayback。如果用户开始跑步,只希望跟踪其位置信息,您的应用应调用 startForeground(),并仅传递 location 服务类型。然后,如果用户想开始播放音频,请再次调用 startForeground() 并传递 location|mediaPlayback

Controlli di runtime del sistema

Il sistema controlla l'utilizzo corretto dei tipi di servizi in primo piano e conferma che l'app abbia richiesto le autorizzazioni di runtime appropriate o utilizzi le API richieste. Ad esempio, il sistema si aspetta che le app che utilizzano il tipo di servizio in primo piano FOREGROUND_SERVICE_TYPE_LOCATION richiedano ACCESS_COARSE_LOCATION o ACCESS_FINE_LOCATION.

Ciò implica che le app devono seguire un ordine di operazioni molto specifico quando richiedono autorizzazioni all'utente e avviano i servizi in primo piano. Le autorizzazioni devono essere richieste e concesse prima che l'app tenti di chiamare startForeground(). Le app che richiedono le autorizzazioni appropriate dopo l'avvio del servizio in primo piano devono modificare questo ordine di operazioni e richiedere l'autorizzazione prima di avviare il servizio in primo piano.

Le specifiche dell'applicazione della piattaforma vengono visualizzate nelle sezioni etichettate come "Requisiti di runtime" nella sezione Casi d'uso previsti e applicazione per ogni tipo di servizio in primo piano di questa pagina.

Casi d'uso previsti e applicazione forzata per ogni tipo di servizio in primo piano

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.

Fotocamera

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 connesso

Tipo di servizio in primo piano da dichiarare nel manifest in
android:foregroundServiceType
connectedDevice
Autorizzazione da dichiarare nel file manifest
FOREGROUND_SERVICE_CONNECTED_DEVICE
Costante da passare a startForeground()
FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE
Prerequisiti di runtime

Deve essere vera almeno una delle seguenti condizioni:

Descrizione

Interazioni con dispositivi esterni che richiedono Bluetooth, NFC, IR, USB o una connessione di rete.

Alternative

Se la tua app deve eseguire il trasferimento continuo di dati su un dispositivo esterno, puoi utilizzare il gestore dei dispositivi complementari. Utilizza l'API di presenza del dispositivo complementare per consentire alla tua app di continuare a funzionare mentre il dispositivo complementare è in portata.

Se la tua app deve cercare dispositivi Bluetooth, ti consigliamo di utilizzare l'API di ricerca Bluetooth.

Sincronizzazione dati

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.

Salute

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

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

注意BODY_SENSORS 和基于传感器的读取运行时权限受“在使用时”限制。因此,除非您已获得 BODY_SENSORS_BACKGROUND(API 级别 33 到 35)或 READ_HEALTH_DATA_IN_BACKGROUND(API 级别 36 及更高级别)权限,否则您无法创建在应用处于后台运行时使用身体传感器的 health 前台服务。如需了解详情,请参阅与启动需要使用时权限的前台服务相关的限制

说明

为健身类别的应用(例如锻炼追踪器)提供支持的所有长时间运行的用例。

Posizione

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

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

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

注意:位置信息运行时权限受“使用期间”限制。因此,除非您已获得 ACCESS_BACKGROUND_LOCATION 运行时权限,否则无法在应用在后台运行时创建 location 前台服务。如需了解详情,请参阅与启动需要“使用时”权限的前台服务相关的限制

说明

需要位置信息使用权的长时间运行的用例,例如导航和位置信息分享。

替代方案

如果您的应用需要在用户到达特定位置时触发,请考虑改用 Geofence API

Contenuti multimediali

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.

Proiezione di contenuti multimediali

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.

Microfono

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

请求并获得 RECORD_AUDIO 运行时权限。

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

说明

在后台继续捕获麦克风内容,例如录音器或通信应用。

Telefonata

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.

Messaggistica remota

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

Servizio di Short

Tipo di servizio in primo piano da dichiarare nel manifest in
android:foregroundServiceType
shortService
Autorizzazione da dichiarare nel file manifest
Nessuna
Costante da passare a startForeground()
FOREGROUND_SERVICE_TYPE_SHORT_SERVICE
Prerequisiti di runtime
Nessuna
Descrizione

Completare rapidamente i lavori critici che non possono essere interrotti o posticipati.

Questo tipo ha alcune caratteristiche uniche:

  • Può essere eseguito solo per un breve periodo di tempo (circa 3 minuti).
  • Nessun supporto per i servizi in primo piano permanenti.
  • Impossibile avviare altri servizi in primo piano.
  • Non richiede un'autorizzazione specifica per tipo, ma richiede comunque l'autorizzazione FOREGROUND_SERVICE.
  • Un shortService può passare a un altro tipo di servizio solo se l'app è attualmente idonea a avviare un nuovo servizio in primo piano.
  • Un servizio in primo piano può modificare il proprio tipo in shortService in qualsiasi momento, a quel punto inizia il periodo di timeout.

Il timeout per shortService inizia dal momento in cui viene chiamato Service.startForeground(). L'app deve chiamare Service.stopSelf() o Service.stopForeground() prima che si verifichi il timeout. In caso contrario, viene chiamato il nuovo Service.onTimeout(), offrendo alle app una breve opportunità di chiamare stopSelf() o stopForeground() per interrompere il servizio.

Poco dopo la chiamata a Service.onTimeout(), l'app entra in uno stato memorizzato nella cache e non è più considerata in primo piano, a meno che l'utente non interagisca attivamente con l'app. Poco dopo che l'app è stata memorizzata nella cache e il servizio non è stato interrotto, l'app riceve un ANR. Il messaggio ANR menziona FOREGROUND_SERVICE_TYPE_SHORT_SERVICE. Per questi motivi, è considerata una best practice implementare il callbackService.onTimeout().

Il richiamata Service.onTimeout() non esiste su Android 13 e versioni precedenti. Se lo stesso servizio viene eseguito su questi dispositivi, non riceve un timeout né un ANR. Assicurati che il servizio si fermi non appena completa l'attività di elaborazione, anche se non ha ancora ricevuto il Service.onTimeout() callback.

È importante notare che se il timeout di shortService non viene rispettato, l'app genera un ANR anche se sono in esecuzione altri servizi in primo piano validi o altri processi del ciclo di vita dell'app.

Se un'app è visibile all'utente o soddisfa una delle esenzioni che consentono l'avvio dei servizi in primo piano dal background, la chiamata Service.StartForeground() di nuovo con il parametro FOREGROUND_SERVICE_TYPE_SHORT_SERVICE prolunga il timeout di altri 3 minuti. Se l'app non è visibile all'utente e non soddisfa una delle esenzioni, qualsiasi tentativo di avviare un altro servizio in primo piano, indipendentemente dal tipo, genera un ForegroundServiceStartNotAllowedException.

Se un utente disattiva l'ottimizzazione batteria per la tua app, quest'ultima è comunque interessata dal timeout di shortService FGS.

Se avvii un servizio in primo piano che include il tipo shortService e un altro tipo di servizio in primo piano, il sistema ignora la dichiarazione del tipo shortService. Tuttavia, il servizio deve comunque rispettare i prerequisiti degli altri tipi dichiarati. Per ulteriori informazioni, consulta la documentazione relativa ai servizi in primo piano.

Uso speciale

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>

Esenzione dal sistema

Tipo di servizio in primo piano da dichiarare nel manifest in
android:foregroundServiceType
systemExempted
Autorizzazione da dichiarare nel file manifest
FOREGROUND_SERVICE_SYSTEM_EXEMPTED
Costante da passare a startForeground()
FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED
Prerequisiti di runtime
Nessuna
Descrizione

Riservato per applicazioni di sistema e integrazioni di sistema specifiche, per continuare a utilizzare i servizi in primo piano.

Per utilizzare questo tipo, un'app deve soddisfare almeno uno dei seguenti criteri:

Applicazione delle norme di Google Play per l'utilizzo dei tipi di servizi in primo piano

如果您的应用以 Android 14 或更高版本为目标平台,您需要在 Play 管理中心的“应用内容”页面(政策 > 应用内容)中声明应用的前台服务类型。如需详细了解如何在 Play 管理中心内声明前台服务类型,请参阅了解前台服务和全屏 intent 要求