Processi e ciclo di vita dell'app
Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Nella maggior parte dei casi, ogni applicazione Android viene eseguita nel proprio processo Linux.
Questo processo viene creato per l'applicazione quando è necessario eseguire parte del codice e rimane in esecuzione finché il sistema non deve recuperare la memoria per l'utilizzo da parte di altre applicazioni e non è più necessario.
Una funzionalità insolita e fondamentale di Android è che il ciclo di vita di un processo dell'applicazione non è controllato direttamente dall'applicazione stessa.
Viene invece determinata dal sistema tramite una combinazione delle parti dell'applicazione
che il sistema sa essere in esecuzione, dell'importanza di queste cose per l'utente
e della quantità di memoria complessiva disponibile nel sistema.
È importante che gli sviluppatori di applicazioni comprendano in che modo i diversi componenti dell'applicazione (in particolare Activity
, Service
e BroadcastReceiver
) influiscono sul ciclo di vita del processo dell'applicazione. Se non utilizzi questi componenti correttamente, il sistema potrebbe interrompere il processo dell'applicazione mentre sta svolgendo un'attività importante.
Un esempio comune di bug del ciclo di vita del processo è un
BroadcastReceiver
che avvia un thread quando
riceve un Intent
nel suo metodo BroadcastReceiver.onReceive()
e poi ritorna dalla funzione. Una volta restituito, il sistema considera che BroadcastReceiver
non sia più attivo e che il relativo processo di hosting non sia più necessario, a meno che non siano attivi altri componenti dell'applicazione.
Di conseguenza, il sistema può interrompere il processo in qualsiasi momento per recuperare la memoria e, con questa operazione, termina il thread generato in esecuzione nel processo. La soluzione a questo problema solitamente consiste nel pianificare un JobService
da BroadcastReceiver
in modo che il sistema sappia che nel processo è in corso un'attività.
Per determinare quali processi terminare quando la memoria è in esaurimento, Android colloca ogni processo in una gerarchia di importanza in base ai componenti in esecuzione e allo stato di questi componenti. In ordine di importanza, questi tipi di processo sono:
- Un processo in primo piano è necessario per ciò che l'utente sta facendo al momento. Vari componenti dell'applicazione possono far sì che il processo contenitore venga considerato in primo piano in modi diversi. Un processo è considerato in primo piano se è soddisfatta una delle seguenti condizioni:
Nel sistema sono presenti solo alcuni di questi processi e vengono terminati solo come ultima risorsa se la memoria è così ridotta che nemmeno questi processi possono continuare a funzionare. In genere, se ciò accade, il dispositivo ha raggiunto uno stato di paging della memoria, pertanto questa azione è necessaria per mantenere reattiva l'interfaccia utente.
- Un processo visibile esegue un'operazione di cui l'utente è attualmente a conoscenza, pertanto l'interruzione ha un impatto negativo significativo sull'esperienza utente. Un processo è considerato visibile nelle seguenti condizioni:
- È in esecuzione un
Activity
visibile all'utente sullo schermo, ma non in primo piano (è stato chiamato il suo metodo onPause()
). Ciò potrebbe accadere, ad esempio, se il Activity
in primo piano viene visualizzato come finestra di dialogo che consente di vedere il Activity
precedente dietro.
- Ha un
Service
in esecuzione come servizio in primo piano tramite Service.startForeground()
(che chiede al sistema di trattare il servizio come qualcosa di noto all'utente o, in sostanza, come se fosse visibile).
- Ospita un servizio utilizzato dal sistema per una determinata funzionalità nota all'utente, ad esempio uno sfondo animato o un servizio di metodo di inserimento.
Il numero di questi processi in esecuzione nel sistema è meno limitato rispetto ai processi in primo piano, ma comunque relativamente controllato. Queste procedure sono considerate estremamente importanti e non vengono interrotte, a meno che non sia necessario per mantenere in esecuzione tutte le procedure in primo piano.
- Un processo di servizio è un processo che contiene un
Service
avviato con il metodo startService()
. Anche se questi
procedimenti non sono direttamente visibili all'utente, in genere svolgono attività
che interessano l'utente (ad esempio il caricamento o il download di dati di rete in background), pertanto il sistema mantiene sempre in esecuzione questi procedimenti
a meno che non sia disponibile memoria sufficiente per conservare tutti i procedimenti in primo piano e visibili.
I servizi in esecuzione da molto tempo (ad esempio 30 minuti o più) potrebbero essere svalutati in termini di importanza per consentire il passaggio del relativo processo all'elenco memorizzato nella cache.
Le procedure che devono essere eseguite per un lungo periodo possono essere create con
setForeground
.
Se si tratta di un processo periodico che richiede un'ora di esecuzione rigorosa, può essere pianificato tramite AlarmManager
.
Per ulteriori informazioni, consulta la sezione Supporto per i worker a lungo termine.
In questo modo si evitano situazioni in cui i servizi a lungo termine che utilizzano risorse eccessive, ad esempio con perdite di memoria, impediscono al sistema di offrire un'esperienza utente ottimale.
- Un processo memorizzato nella cache è un processo che al momento non è necessario, pertanto il sistema è libero di interromperlo in base alle necessità quando risorse come la memoria sono necessarie altrove. In un sistema con comportamento normale, questi sono gli unici processi coinvolti nella gestione delle risorse.
Un sistema ben funzionante ha sempre a disposizione più processi memorizzati nella cache, per passare in modo efficiente da un'applicazione all'altra e termina regolarmente le app memorizzate nella cache in base alle esigenze.
Solo in situazioni molto critiche il sistema arriva a un punto in cui tutti i processi memorizzati nella cache vengono interrotti e deve iniziare a interrompere i processi di servizio.
Poiché i processi memorizzati nella cache possono essere interrotti dal sistema in qualsiasi momento, le app devono interrompere tutte le attività mentre sono nello stato memorizzato nella cache. Se l'app deve eseguire operazioni fondamentali per l'utente, deve utilizzare una delle API sopra indicate per eseguire le operazioni da uno stato di processo attivo.
I processi memorizzati nella cache spesso contengono una o più istanze Activity
che non sono attualmente visibili all'utente (il loro metodo Activity
è stato chiamato e ha restituito un valore).onStop()
A condizione che implementino correttamente il ciclo di vita di Activity
quando il sistema interrompe queste procedure, l'esperienza dell'utente non viene influenzata quando torna nell'app.
Può ripristinare lo stato salvato in precedenza quando l'attività associata viene ricreata in
una nuova procedura. Tieni presente che non è garantito che onDestroy()
viene chiamato nel caso in cui un processo venga interrotto dal sistema.
Per maggiori dettagli, vedi Activity
.
A partire da Android 13, un processo dell'app potrebbe ricevere un tempo di esecuzione limitato o nullo finché non entra in uno degli stati di ciclo di vita attivi sopra indicati.
I processi memorizzati nella cache vengono conservati in un elenco. Il criterio di ordinamento esatto per questo elenco
è un dettaglio di implementazione della piattaforma. In genere, cerca di mantenere le attività più utili, ad esempio quelle che ospitano l'applicazione Home dell'utente o l'ultima attività visualizzata dall'utente, prima di altri tipi di attività. È possibile applicare anche altri criteri per l'interruzione dei processi, ad esempio l'impostazione di limiti rigidi sul numero di processi consentiti o la limitazione del tempo di memorizzazione nella cache di un processo.
Quando decide come classificare un processo, il sistema basa la sua decisione sul livello più importante trovato tra tutti i componenti attualmente attivi nel processo.
Consulta la documentazione di Activity
, Service
e
BroadcastReceiver
per ulteriori dettagli su come ciascuno di questi componenti contribuisce al ciclo di vita complessivo di un processo e dell'applicazione.
La priorità di un processo può essere aumentata anche in base ad altre dipendenze. Ad esempio, se il processo A è associato a un
Service
con il
flag Context.BIND_AUTO_CREATE
o utilizza un
ContentProvider
nel processo B, la classificazione del processo B è sempre almeno importante quanto quella del processo A.
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-07-27 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-07-27 UTC."],[],[],null,["# Processes and app lifecycle\n\nIn most cases, every Android application runs in its own Linux process.\nThis process is created for the application when some of its code needs to\nrun and remains running until the system needs to reclaim its memory for use\nby other applications and it is no longer needed.\n\nAn unusual and fundamental feature of Android is that an application process's\nlifetime *isn't* directly controlled by the application itself.\nInstead, it is determined by the system through a combination of the parts of the application\nthat the system knows are running, how important these things are to the user,\nand how much overall memory is available in the system.\n\nIt is important that\napplication developers understand how different application components\n(in particular [Activity](/reference/android/app/Activity), [Service](/reference/android/app/Service),\nand [BroadcastReceiver](/reference/android/content/BroadcastReceiver)) impact the lifetime\nof the application's process. **Not using these components correctly can\nresult in the system killing the application's process while it is doing\nimportant work.**\n\nA common example of a process lifecycle bug is a\n`BroadcastReceiver` that starts a thread when it\nreceives an `Intent` in its [BroadcastReceiver.onReceive()](/reference/android/content/BroadcastReceiver#onReceive(android.content.Context, android.content.Intent))\nmethod and then returns from the function. Once it returns, the system\nconsiders the `BroadcastReceiver` to no longer be active, and its hosting\nprocess to no longer be needed, unless other application components are active in\nit.\n\n\nSo, the system can kill the process at any time to reclaim memory, and in doing so,\nit terminates the spawned thread running in the process. The solution to this problem\nis typically to schedule a [JobService](/reference/android/app/job/JobService)\nfrom the `BroadcastReceiver` so the\nsystem knows that there is active work occurring in the process.\n\nTo determine which processes to kill when low on memory, Android\nplaces each process into an importance hierarchy based on the components running in\nthem and the state of those components. In order of importance, these process types are:\n\n1. A **foreground process** is one that is required for what the user is currently doing. Various application components can cause its containing process to be considered foreground in different ways. A process is considered to be in the foreground if any of the following conditions hold:\n - It is running an [Activity](/reference/android/app/Activity) at the top of the screen that the user is interacting with (its [onResume()](/reference/android/app/Activity#onResume()) method has been called).\n - It has a [BroadcastReceiver](/reference/android/content/BroadcastReceiver) that is currently running (its [BroadcastReceiver.onReceive()](/reference/android/content/BroadcastReceiver#onReceive(android.content.Context, android.content.Intent)) method is executing).\n - It has a [Service](/reference/android/app/Service) that is currently executing code in one of its callbacks ([Service.onCreate()](/reference/android/app/Service#onCreate()), [Service.onStart()](/reference/android/app/Service#onStart(android.content.Intent, int)), or [Service.onDestroy()](/reference/android/app/Service#onDestroy())).\n2. There are only ever a few such processes in the system, and these are only killed as a last resort if memory is so low that not even these processes can continue to run. Generally, if this happens the device has reached a memory paging state, so this action is required to keep the user interface responsive.\n3. A **visible process** is doing work that the user is currently aware of, so killing it has a noticeable negative impact on the user experience. A process is considered visible in the following conditions:\n - It is running an [Activity](/reference/android/app/Activity) that is visible to the user on-screen but not in the foreground (its [onPause()](/reference/android/app/Activity#onPause()) method has been called). This might occur, for example, if the foreground `Activity` is displayed as a dialog that lets the previous `Activity` be seen behind it.\n - It has a [Service](/reference/android/app/Service) that is running as a foreground service, through [Service.startForeground()](/reference/android/app/Service#startForeground(int, android.app.Notification)) (which asks the system to treat the service as something the user is aware of, or essentially as if it were visible).\n - It is hosting a service that the system is using for a particular feature that the user is aware of, such as a live wallpaper or an input method service.\n\n The number of these processes running in the system is less bounded than foreground\n processes, but still relatively controlled. These processes are\n considered extremely important and aren't killed unless doing so is\n required to keep all foreground processes running.\n4. A **service process** is one holding a [Service](/reference/android/app/Service) that has been started with the [startService()](/reference/android/content/Context#startService(android.content.Intent)) method. Though these processes are not directly visible to the user, they are generally doing things that the user cares about (such as background network data upload or download), so the system always keeps such processes running unless there is not enough memory to retain all foreground and visible processes.\n\n Services that have been running for a long time (such as 30 minutes or more) might be\n demoted in importance to let their process drop to the cached list.\n\n Processes that do need to be run over a long period can be created with\n [setForeground](/reference/kotlin/androidx/work/CoroutineWorker#setForeground(androidx.work.ForegroundInfo)).\n If it is a periodic process that requires strict time of execution, it can be\n scheduled through the [AlarmManager](/reference/android/app/AlarmManager).\n For more information, refer to [Support for long-running workers](/topic/libraries/architecture/workmanager/advanced/long-running).\n This helps avoid situations where long-running services that use excessive resources, for\n example, by leaking memory, prevent the system from delivering a good user experience.\n5. A **cached process** is one that is not currently needed, so the system is free to kill it as needed when resources like memory are needed elsewhere. In a normally behaving system, these are the only processes involved in resource management.\n\n \u003cbr /\u003e\n\n A well-running system has multiple cached processes always available, for efficient\n switching between applications, and regularly kills the cached apps as needed.\n Only in very critical situations does the system get to a point where\n all cached processes are killed and it must start killing service processes.\n\n Since cached processes can be killed by the system at any time, apps should cease all work while\n in the cached state. If user-critical work must be performed by the app,\n it should use one of the above APIs to run work from an active process state.\n\n Cached processes often hold one or more [Activity](/reference/android/app/Activity) instances\n that are not currently visible to the user (their\n [onStop()](/reference/android/app/Activity#onStop()) method has been called and has returned).\n Provided they implement their `Activity` lifecycle correctly when the system\n kills such processes, it doesn't impact the user's experience when returning to that app.\n It can restore the previously saved state when the associated activity recreates in\n a new process. Be aware that [onDestroy()](/guide/components/activities/activity-lifecycle#ondestroy)\n is not guaranteed to be called in the case that a process is killed by the system.\n For more details, see [Activity](/reference/android/app/Activity).\n\n Starting in Android 13, an app process may receive limited or no execution time until it enters\n one of the above active lifecycle states.\n\n Cached processes are kept in a list. The exact ordering policy for this list\n is an implementation detail of the platform. Generally, it tries to keep more\n useful processes, such as those hosting the user's home application or the last activity the user saw,\n before other types of processes. Other policies for killing processes can also\n be applied, like setting hard limits on the number of processes allowed or limiting the amount of\n time a process can stay continually cached.\n\nWhen deciding how to classify a process, the system bases its decision on the most\nimportant level found among all the components currently active in the process.\nSee the [Activity](/reference/android/app/Activity), [Service](/reference/android/app/Service), and\n[BroadcastReceiver](/reference/android/content/BroadcastReceiver) documentation for more detail on how\neach of these components contributes to the overall lifecycle of a process and of\nthe application.\n\nA process's priority might also be increased based on other dependencies\na process has to it. For example, if process A has bound to a\n[Service](/reference/android/app/Service) with\nthe [Context.BIND_AUTO_CREATE](/reference/android/content/Context#BIND_AUTO_CREATE)\nflag or is using a\n[ContentProvider](/reference/android/content/ContentProvider) in process B, then process B's\nclassification is always at least as important as process A's."]]