Tipi di servizi in primo piano

A partire da Android 14 (livello API 34), devi dichiarare un tipo di servizio appropriato per ogni servizio in primo piano. Ciò significa che devi dichiarare il tipo di servizio nel manifest dell'app e richiedere anche l'autorizzazione per il servizio in primo piano appropriata per quel tipo (oltre a richiedere l'autorizzazione FOREGROUND_SERVICE). Inoltre, a seconda del tipo di servizio in primo piano, potresti dover richiedere le autorizzazioni di runtime prima di avviare il servizio.

Fotocamera

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

请求并被授予 CAMERA 运行时权限

说明

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

Dispositivo connesso

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

Deve essere vera almeno una delle seguenti condizioni:

Descrizione

Le interazioni con dispositivi esterni che richiedono una connessione di rete, Bluetooth, NFC, IR, USB.

Alternative

Se la tua app deve effettuare un trasferimento di dati continuo su un dispositivo esterno, valuta l'utilizzo di Gestione dispositivi associati. Utilizza l'API companion device Presence per mantenere l'app in esecuzione quando il dispositivo associato è nel raggio d'azione.

Se la tua app deve cercare dispositivi Bluetooth, valuta la possibilità di utilizzare l'API Bluetooth Scan.

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

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.

Posizione

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.

Contenuti multimediali

要在清单中声明的前台服务类型,位于
android:foregroundServiceType
mediaPlayback
要在清单中声明的权限
FOREGROUND_SERVICE_MEDIA_PLAYBACK
要传递给 startForeground() 的常量
FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK
运行时前提条件
说明

在后台继续播放音频或视频。在 Android TV 上支持数字视频录制 (DVR) 功能。

替代方案

如果您要显示画中画视频,请使用画中画模式

Elaborazione contenuti multimediali in corso

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.

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

Tipo di servizio in primo piano da dichiarare nel manifest in
android:foregroundServiceType
microphone
Autorizzazione da dichiarare nel manifest
FOREGROUND_SERVICE_MICROPHONE
Costante da passare a startForeground()
FOREGROUND_SERVICE_TYPE_MICROPHONE
Prerequisiti di runtime

Richiedi e ottieni l'autorizzazione di runtime RECORD_AUDIO.

Descrizione

Continua l'acquisizione del microfono in background, ad esempio per registratori vocali o app di comunicazione.

Telefonata

Tipo di servizio in primo piano da dichiarare nel manifest in
android:foregroundServiceType
phoneCall
Autorizzazione da dichiarare nel manifest
FOREGROUND_SERVICE_PHONE_CALL
Costante da passare a startForeground()
FOREGROUND_SERVICE_TYPE_PHONE_CALL
Prerequisiti di runtime

Almeno una di queste condizioni deve essere vera:

  • L'app è l'app di connessione a internet predefinita tramite il ruolo ROLE_DIALER.
Descrizione

Continua una chiamata in corso utilizzando le API ConnectionService.

Alternative

Se devi effettuare chiamate telefoniche, videochiamate o chiamate VoIP, valuta la possibilità di utilizzare la libreria android.telecom.

Valuta la possibilità di utilizzare CallScreeningService per filtrare le chiamate.

Messaggistica remota

Tipo di servizio in primo piano da dichiarare nel file manifest in
android:foregroundServiceType
remoteMessaging
Autorizzazione da dichiarare nel manifest
FOREGROUND_SERVICE_REMOTE_MESSAGING
Costante per passare a startForeground()
FOREGROUND_SERVICE_TYPE_REMOTE_MESSAGING
Prerequisiti di runtime
Nessuno
Descrizione
Trasferisci messaggi da un dispositivo a un altro. Agevola la continuità delle attività di messaggistica di un utente quando cambia dispositivo.

Servizio breve

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 call Service.stopSelf() or Service.stopForeground() before the timeout occurs. Otherwise, the new Service.onTimeout() is called, giving apps a brief opportunity to call stopSelf() or stopForeground() 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 mentions FOREGROUND_SERVICE_TYPE_SHORT_SERVICE. For these reasons, it's considered best practice to implement the Service.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 the Service.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 the FOREGROUND_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 a ForegroundServiceStartNotAllowedException.

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

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:

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

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