Scegli l'API giusta per mantenere attivo il dispositivo
Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Quando l'utente lascia inattivo il dispositivo Android, questo entra rapidamente in
modalità sospensione per evitare di scaricare la batteria. Tuttavia, a volte un'app deve impedire alla CPU di passare allo stato di sospensione. In alcuni casi, l'app potrebbe dover mantenere lo schermo acceso mentre è in funzione. In altri casi, l'app
non ha bisogno di mantenere lo schermo attivo, ma la CPU deve rimanere attiva.
L'approccio che adotti dipende dalle esigenze della tua app. Tuttavia, una regola generale
è che devi utilizzare l'approccio più leggero possibile per ridurre al minimo l'impatto
della tua app sulle risorse di sistema. Questo documento ti aiuta a scegliere la tecnologia Android corretta per la tua situazione.
Scegliere la tecnologia giusta
L'opzione migliore per mantenere attivo il dispositivo dipende dalle esigenze della tua app. Questa
sezione ti aiuta a scegliere l'approccio giusto.
La tua app deve mantenere lo schermo acceso?
Se Sì, consulta Mantenere lo schermo acceso. Potrebbe esistere un'API per scopi speciali che fa al caso tuo. Ad esempio, se stai implementando un'interfaccia utente per le chiamate, puoi utilizzare il framework Android Telecom, che mantiene lo schermo acceso quando necessario. Se non esiste un'API
per scopi speciali per la tua situazione, puoi utilizzare l'API keepScreenOn.
La tua app esegue un servizio in primo piano e devi mantenere il dispositivo
attivo quando lo schermo è spento mentre il servizio è in esecuzione?
Se la risposta è No, non è necessario mantenere attivo il dispositivo. Se l'utente
interagisce attivamente con l'app, il dispositivo rimane attivo. Se l'utente non interagisce con la tua app e non esegui un servizio in primo piano, devi consentire al dispositivo di entrare in modalità di sospensione quando necessario. Se devi solo assicurarti che alcune attività vengano eseguite mentre l'utente non utilizza l'app, consulta la documentazione relativa alle attività in background per trovare l'opzione migliore.
Se Sì, prima conferma di dover utilizzare un servizio in primo piano. A seconda della tua situazione, potrebbero essere disponibili API
per scopi speciali che puoi utilizzare per soddisfare le tue esigenze anziché un servizio in primo piano.
Puoi trovare informazioni su questi nella documentazione del servizio in primo piano. Ad esempio, se devi monitorare la posizione dell'utente, potresti utilizzare l'API Geofencing anziché un servizio in primo piano location.
L'esperienza utente sarebbe compromessa se il dispositivo venisse sospeso mentre
il servizio in primo piano è in esecuzione e lo schermo del dispositivo è spento? (Ad esempio, se utilizzi un servizio in primo piano per aggiornare le notifiche, non si tratterebbe di una cattiva esperienza utente se il dispositivo è sospeso.)
Se No, non utilizzare un wakelock. L'azione riprende
automaticamente quando l'utente interagisce con il dispositivo, che esce
dalla sospensione.
Se la tua app esegue una delle seguenti operazioni, non devi impostare un wake lock
manualmente. Le seguenti azioni e API mantengono attivo il dispositivo.
Se riproduci audio, il sistema audio imposta e gestisce un wake lock per te, quindi non devi farlo manualmente.
Se utilizzi API o librerie di pianificazione delle attività come WorkManager,
JobScheduler o DownloadManager, il sistema o la libreria acquisisce
un wakelock attribuito alla tua app.
Alcuni sensori del dispositivo sono sensori di riattivazione; puoi utilizzare SensorManager
per fare in modo che questi sensori riattivino il dispositivo quando hanno dati da segnalare. Per
controllare se un sensore è un sensore di riattivazione, chiama il numero Sensor.isWakeUpSensor.
Se programmi una sveglia, il dispositivo si riattiva quando
suona la sveglia, anche se l'app non è in esecuzione.
I campioni di contenuti e codice in questa pagina sono soggetti alle licenze descritte nella Licenza per i contenuti. Java e OpenJDK sono marchi o marchi registrati di Oracle e/o delle sue società consociate.
Ultimo aggiornamento 2025-09-08 UTC.
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Mancano le informazioni di cui ho bisogno","missingTheInformationINeed","thumb-down"],["Troppo complicato/troppi passaggi","tooComplicatedTooManySteps","thumb-down"],["Obsoleti","outOfDate","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Problema relativo a esempi/codice","samplesCodeIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 2025-09-08 UTC."],[],[],null,["When the user leaves their Android-powered device idle, it quickly goes into the\nsuspend state to avoid draining the battery. However, there are times when an\napp needs to prevent the CPU from going to the suspend state. In some cases, the\napp may need to keep the screen on while it's working. In other cases, the app\ndoesn't need to keep the screen on but still needs the CPU to be active.\n\nThe approach you take depends on the needs of your app. However, a general rule\nis that you should use the most lightweight approach possible, to minimize your\napp's impact on system resources. This document helps you choose the correct\nAndroid technology for your situation.\n| **Note:** You may be familiar with **wake locks**. An app can set a wake lock to keep the device from suspending. However, using a wake lock can quickly drain the device battery. You should only use a wake lock if there's no other option that will do what you need. If you do use a wake lock, you should release it as soon as possible.\n\nChoose the right technology\n\nThe best option for keeping your device awake depends on your app's needs. This\nsection helps you choose the right approach.\n\n- Does your app need to keep the screen on?\n - If **Yes** , see [Keep the screen on](/develop/background-work/background-tasks/awake/screen-on). There may be a special-purpose API that does what you need; for example, if you're implementing a phone-call UI, you can use the [Android telecom\n framework](/reference/android/telecom/package-summary), which keeps the screen on when needed. If there's no special purpose API for your situation, you can use the `keepScreenOn` API.\n- Is your app running a foreground service, and you need to keep the device awake when screen is off while the service is running?\n - If **No** , you do not need to keep the device awake. If the user is actively interacting with the app, the device will stay awake. If the user is not interacting with your app and you are not running a foreground service, you should let the device go into suspend mode when necessary. If you just need to make sure some work gets done while the user is away from the app, see the [background tasks](/develop/background-work/background-tasks) documentation to find the best option.\n - If **Yes** , first confirm that you actually need to use a foreground service. Depending on your situation, there may be some special-purpose API you can use to accomplish your need instead of a foreground service. You can find information about these [in the Foreground Service\n documentation](/develop/background-work/services/fgs/service-types). For example, if you need to track the user's location, you might be able to use the [geofencing API](/develop/sensors-and-location/location/geofencing) instead of a `location` foreground service.\n- Would it be detrimental to the user experience if the device suspends while the foreground service is running and the device screen is off? (For example, if you're using a foreground service to update notifications, it wouldn't be a bad user experience if the device is suspended.)\n - If **No**, do not use a wake lock. The action resumes automatically once the user engages with their device, which takes it out of suspend.\n - If **Yes** , you might need to [use a wake lock](/develop/background-work/background-tasks/awake/wakelock). However, you should still check to see if you're already using an API or doing an action that declares a wake lock on your behalf, as discussed in [Actions that keep the device awake](#actions-keep).\n\nActions that keep the device awake\n\nIf your app is doing any of the following, you don't need to set a wake lock\nyourself. The following actions and APIs all keep the device awake for you.\n\n- If you're playing audio, the audio system sets and manages a wake lock for you; you don't need to do it yourself.\n- If you're using task scheduling APIs or libraries such as [WorkManager](/develop/background-work/background-tasks/persistent), [`JobScheduler`](/reference/android/app/job/JobScheduler), or [`DownloadManager`](/reference/android/app/DownloadManager), the system or library acquires a wake lock that is attributed to your app.\n- If you're using [Media3 ExoPlayer](/media/media3/exoplayer), you can use [`ExoPlayer.setWakeMode()`](/reference/androidx/media3/exoplayer/ExoPlayer#setWakeMode(int)) to have the player set a wake lock for you.\n- Certain device sensors are wake-up sensors; you can use [`SensorManager`](/reference/android/hardware/SensorManager) to have those sensors wake up the device when they have data to report. To check if a sensor is a wake-up sensor, call [`Sensor.isWakeUpSensor`](/reference/android/hardware/Sensor#isWakeUpSensor())).\n- If you [schedule an alarm](/develop/background-work/services/alarms), the device wakes up when the alarm goes off, even if your app is not running.\n\nSee also\n\n- [Use wake locks](/develop/background-work/background-tasks/awake/wakelock)\n- [Keep the screen on](/develop/background-work/background-tasks/awake/screen-on)"]]