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 devi anche richiedere 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 avviarlo.
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- Description
Continue to access the camera from the background, such as video chat apps that allow for multitasking.
Dispositivo connesso
- Foreground service type to declare in manifest under
android:foregroundServiceType
connectedDevice
- Permission to declare in your manifest
FOREGROUND_SERVICE_CONNECTED_DEVICE
- Constant to pass to
startForeground()
FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE
- Runtime prerequisites
At least one of the following conditions must be true:
Declare at least one of the following permissions in your manifest:
Request and be granted at least one of the following runtime permissions:
- Description
Interactions with external devices that require a Bluetooth, NFC, IR, USB, or network connection.
- Alternatives
If your app needs to do continuous data transfer to an external device, consider using the companion device manager instead. Use the companion device presence API to help your app stay running while the companion device is in range.
If your app needs to scan for bluetooth devices, consider using the Bluetooth scan API instead.
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:
Declare the
HIGH_SAMPLING_RATE_SENSORS
permission in your manifest.Request and be granted at least one of the following runtime permissions:
BODY_SENSORS
on API 35 and lowerREAD_HEART_RATE
READ_SKIN_TEMPERATURE
READ_OXYGEN_SATURATION
ACTIVITY_RECOGNITION
- 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
- 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
- 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:
- When the transcoding operation finishes or reaches a failure state, have the
service call
Service.stopForeground()
andService.stopSelf()
to stop the service completely.
- When the transcoding operation finishes or reaches a failure state, have the
service call
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 callService.stopSelf()
. If the service does not callService.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
- 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.- Description
Continue microphone capture from the background, such as voice recorders or communication apps.
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 has declared the
MANAGE_OWN_CALLS
permission in its manifest file.
- App has declared the
- App is the default dialer app through the
ROLE_DIALER
role.
- App is the default dialer app through the
- 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
- 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.
Servizio breve
- 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 chiamareService.stopSelf()
oService.stopForeground()
prima che si verifichi il timeout. In caso contrario, viene chiamato il nuovoService.onTimeout()
, offrendo alle app una breve opportunità di chiamarestopSelf()
ostopForeground()
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 menzionaFOREGROUND_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 ilService.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 parametroFOREGROUND_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 unForegroundServiceStartNotAllowedException
.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 tiposhortService
. 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 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>
Esenzione dal sistema
- Tipo di servizio in primo piano da dichiarare nel file manifest in
android:foregroundServiceType
systemExempted
- Autorizzazione da dichiarare nel manifest
FOREGROUND_SERVICE_SYSTEM_EXEMPTED
- Costante per passare a
startForeground()
FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED
- Prerequisiti di runtime
- Nessuno
- 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:
- Il dispositivo è in modalità demo
- L'app è un proprietario del dispositivo
- L'app è proprietario di Profiler
- App per la sicurezza con il ruolo
ROLE_EMERGENCY
- App Amministratore dispositivo
- App con autorizzazione
SCHEDULE_EXACT_ALARM
oUSE_EXACT_ALARM
App VPN (configurate con Impostazioni > Rete e internet > VPN)
In caso contrario, la dichiarazione di questo tipo fa sì che il sistema restituisca un elemento
ForegroundServiceTypeNotAllowedException
.
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.