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

Tipo di servizio in primo piano da dichiarare nel manifest in android:foregroundServiceType
camera
Autorizzazione da dichiarare nel manifest
FOREGROUND_SERVICE_CAMERA
Costante da passare a startForeground()
FOREGROUND_SERVICE_TYPE_CAMERA
Prerequisiti di runtime

Richiedere e ottenere l'autorizzazione di runtime CAMERA

Descrizione

Continua per accedere alla fotocamera dallo sfondo, ad esempio le app di video chat che consentono il multitasking.

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

Tipo di servizio in primo piano da dichiarare nel manifest in
android:foregroundServiceType
health
Autorizzazione da dichiarare nel file manifest
FOREGROUND_SERVICE_HEALTH
Costante da passare a startForeground()
FOREGROUND_SERVICE_TYPE_HEALTH
Prerequisiti di runtime

Deve essere vera almeno una delle seguenti condizioni:

Descrizione

Eventuali casi d'uso di lunga durata per supportare le app nella categoria fitness, come i tracker per l'esercizio fisico.

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

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.

Elaborazione contenuti multimediali in corso

Tipo di servizio in primo piano da dichiarare nel file manifest in
android:foregroundServiceType
mediaProcessing
Autorizzazione da dichiarare nel manifest
FOREGROUND_SERVICE_MEDIA_PROCESSING
Costante per passare a startForeground()
FOREGROUND_SERVICE_TYPE_MEDIA_PROCESSING
Prerequisiti di runtime
Nessuno
Descrizione

Servizio per l'esecuzione di operazioni dispendiose in termini di tempo sugli asset multimediali, come la conversione dei contenuti multimediali in formati diversi. Il sistema consente l'esecuzione di questo servizio per un tempo limitato; in circostanze normali, questo limite di tempo è di 6 ore ogni 24. Questo limite è condiviso da tutti i mediaProcessing servizi in primo piano di un'app.

L'app deve interrompere manualmente il servizio di elaborazione dei contenuti multimediali nel seguente scenario:

Se viene raggiunto il periodo di timeout, il sistema chiama il metodo Service.onTimeout(int, int) del servizio. In questo momento, il servizio ha pochi secondi per chiamare Service.stopSelf(). Se il servizio non chiama Service.stopSelf(), si verificherà un errore ANR con questo messaggio di errore: "Un servizio in primo piano di <fgs_type> non è stato interrotto durante il timeout: <component_name>".

Nota: Service.onTimeout(int, int) non è disponibile su Android 14 o versioni precedenti. Sui dispositivi che eseguono queste versioni, se un servizio di elaborazione multimediale raggiunge il periodo di timeout, il sistema memorizza immediatamente l'app nella cache. Per questo motivo, l'app non deve attendere di ricevere una notifica di timeout. Dovrebbe invece terminare il servizio in primo piano o passare a un servizio in background non appena opportuno.

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

Se la tua app ha come target Android 14 o versioni successive, devi dichiarare i tipi di servizi in primo piano della tua app nella pagina Contenuti app di Play Console (Norme > Contenuti app). Per ulteriori informazioni su come dichiarare i tipi di servizio in primo piano in Play Console, consulta Informazioni sui requisiti relativi al servizio in primo piano e all'intent a schermo intero.