處理程序與應用程式生命週期
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
在大多數情況下,每個 Android 應用程式都會在其專屬的 Linux 程序中執行。當應用程式需要執行部分程式碼時,系統會為該應用程式建立此處理程序,並持續執行,直到系統需要回收記憶體供其他應用程式使用,且該處理程序不再需要為止。
Android 的一項特殊且基本功能,是應用程式程序的生命週期「不會」直接由應用程式本身控管。而是由系統根據系統知道正在執行的應用程式部分、這些部分對使用者的重要性,以及系統可用的整體記憶體量來決定。
應用程式開發人員必須瞭解不同應用程式元件 (特別是 Activity
、Service
和 BroadcastReceiver
) 如何影響應用程式程序的生命週期。如果未正確使用這些元件,系統可能會在應用程式執行重要工作時終止其程序。
程序生命週期錯誤的常見例子是 BroadcastReceiver
,當其在 BroadcastReceiver.onReceive()
方法中收到 Intent
時會啟動執行緒,然後從函式中傳回。返回後,系統會將 BroadcastReceiver
視為不再處於活動狀態,且不再需要其代管程序,除非其他應用程式元件在其中處於活動狀態。
因此,系統可隨時終止程序來回收記憶體,並在執行此操作時終止在程序中執行的衍生執行緒。解決這個問題的方法通常是從 BroadcastReceiver
排定 JobService
,讓系統知道程序中正在進行中的作業。
為了決定在記憶體不足時要終止哪些程序,Android 會根據執行中的元件和這些元件的狀態,為每個程序排出重要性階層。依重要性排序,這些程序類型如下:
- 前景程序是指使用者目前正在執行的程序所需的程序。各種應用程式元件可能會以不同方式,讓包含的程序視為前景。如果符合下列任一條件,系統就會將程序視為處於前景:
系統中只有少數這類程序,而且只有在記憶體不足,連這些程序也無法繼續執行時,才會終止這些程序。一般來說,如果發生這種情況,表示裝置已達到記憶體分頁狀態,因此必須執行這項動作,才能讓使用者介面保持回應。
- 可見的程序會執行使用者目前瞭解的工作,因此終止該程序會對使用者體驗造成明顯的負面影響。在下列情況下,系統會將程序視為可見:
在系統中執行的這些程序數量雖然不像前景程序那麼受限,但仍受到相對控制。這些程序被視為極為重要,除非需要維持所有前景程序執行,否則不會終止。
- 服務程序是指持有已透過
startService()
方法啟動的 Service
。雖然使用者無法直接看到這些程序,但這些程序通常會執行使用者在意的作業 (例如背景網路資料上傳或下載),因此系統會一律保留這類程序,除非記憶體不足,無法保留所有前景和可見程序。已執行一段時間 (例如 30 分鐘以上) 的服務,可能會降級為次要,讓其程序降至快取清單。
您可以使用 setForeground
建立需要長時間執行的程序。如果這是需要嚴格執行時間的週期性程序,可以透過 AlarmManager
排程。詳情請參閱「支援長時間執行的 worker」。這有助於避免長時間執行的服務使用過多資源 (例如記憶體外洩),導致系統無法提供良好的使用者體驗。
- 快取程序是指目前不需要的程序,因此當系統需要記憶體等資源時,可以視需要終止這些程序。在正常運作的系統中,只有這些程序會涉及資源管理。
運作良好的系統會隨時提供多個快取程序,以便在應用程式之間切換,並視需要定期關閉快取的應用程式。只有在非常嚴重的情況下,系統才會終止所有快取的程序,並開始終止服務程序。
由於系統隨時可能終止快取程序,因此應用程式應在快取狀態下停止所有工作。如果應用程式必須執行對使用者至關重要的作業,則應使用上述任一 API,在有效程序狀態下執行作業。
快取的程序通常會保留一或多個使用者目前無法看到的 Activity
例項 (其 onStop()
方法已呼叫並傳回)。只要系統在終止這類程序時正確實作 Activity
生命週期,就不會影響使用者返回該應用程式的體驗。當相關活動在新程序中重建時,系統可以還原先前儲存的狀態。請注意,如果系統終止程序,系統不保證會呼叫 onDestroy()
。詳情請參閱 Activity
。
從 Android 13 開始,應用程式處理程序可能會在進入上述任一有效生命週期狀態前,收到有限或沒有執行時間。
快取的程序會保留在清單中。這份清單的確切排序政策是平台的實作細節。一般來說,系統會嘗試保留較實用的程序,例如負責代管使用者主畫面應用程式或使用者最後看到的活動的程序,再保留其他類型的程序。您也可以套用其他程序終止政策,例如設定允許的程序數量硬性限制,或限制程序可持續快取的時間長度。
在決定如何分類程序時,系統會根據目前在程序中有效的所有元件中找到的最重要層級做出決定。如要進一步瞭解這些元件如何為程序和應用程式的整體生命週期做出貢獻,請參閱 Activity
、Service
和 BroadcastReceiver
的說明文件。
程序的優先順序也可能會根據程序的其他依附元件而提高。舉例來說,如果程序 A 已繫結至具有 Context.BIND_AUTO_CREATE
標記的 Service
,或是在程序 B 中使用 ContentProvider
,則程序 B 的分類至少會與程序 A 一樣重要。
這個頁面中的內容和程式碼範例均受《內容授權》中的授權所規範。Java 與 OpenJDK 是 Oracle 和/或其關係企業的商標或註冊商標。
上次更新時間:2025-07-27 (世界標準時間)。
[null,null,["上次更新時間:2025-07-27 (世界標準時間)。"],[],[],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."]]