Quy trình và chu kỳ ứng dụng
Sử dụng bộ sưu tập để sắp xếp ngăn nắp các trang
Lưu và phân loại nội dung dựa trên lựa chọn ưu tiên của bạn.
Trong hầu hết các trường hợp, mọi ứng dụng Android đều chạy trong quy trình Linux riêng.
Quy trình này được tạo cho ứng dụng khi một số mã của ứng dụng cần chạy và tiếp tục chạy cho đến khi hệ thống cần lấy lại bộ nhớ để các ứng dụng khác sử dụng và không cần đến nữa.
Một tính năng cơ bản và khác thường của Android là thời gian hoạt động của quy trình ứng dụng không do chính ứng dụng kiểm soát trực tiếp.
Thay vào đó, hệ thống sẽ xác định mức độ ưu tiên thông qua việc kết hợp các phần của ứng dụng mà hệ thống biết là đang chạy, mức độ quan trọng của các phần này đối với người dùng và tổng dung lượng bộ nhớ có sẵn trong hệ thống.
Điều quan trọng là nhà phát triển ứng dụng phải hiểu cách các thành phần ứng dụng khác nhau (đặc biệt là Activity
, Service
và BroadcastReceiver
) tác động đến thời gian hoạt động của quy trình ứng dụng. Việc không sử dụng đúng các thành phần này có thể dẫn đến việc hệ thống chấm dứt quy trình của ứng dụng trong khi ứng dụng đang thực hiện công việc quan trọng.
Một ví dụ phổ biến về lỗi vòng đời quy trình là BroadcastReceiver
bắt đầu một luồng khi nhận được Intent
trong phương thức BroadcastReceiver.onReceive()
rồi trả về từ hàm. Sau khi trả về, hệ thống sẽ coi BroadcastReceiver
không còn hoạt động và quy trình lưu trữ của BroadcastReceiver
không còn cần thiết nữa, trừ phi các thành phần ứng dụng khác đang hoạt động trong đó.
Vì vậy, hệ thống có thể chấm dứt quy trình bất cứ lúc nào để lấy lại bộ nhớ. Khi đó, hệ thống sẽ chấm dứt luồng được tạo đang chạy trong quy trình. Giải pháp cho vấn đề này thường là lên lịch JobService
từ BroadcastReceiver
để hệ thống biết rằng có công việc đang diễn ra trong quy trình.
Để xác định quy trình nào cần loại bỏ khi bộ nhớ sắp hết, Android đặt từng quy trình vào một hệ phân cấp mức độ quan trọng dựa trên các thành phần đang chạy trong quy trình đó và trạng thái của các thành phần đó. Theo thứ tự quan trọng, các loại quy trình này là:
- Quy trình trên nền trước là quy trình bắt buộc đối với những việc người dùng đang làm. Nhiều thành phần ứng dụng có thể khiến quy trình chứa ứng dụng được coi là nền trước theo nhiều cách. Một quy trình được coi là ở nền trước nếu đáp ứng bất kỳ điều kiện nào sau đây:
Hệ thống chỉ có một vài quy trình như vậy và các quy trình này chỉ bị loại bỏ như biện pháp cuối cùng nếu bộ nhớ quá thấp đến mức ngay cả các quy trình này cũng không thể tiếp tục chạy. Nhìn chung, nếu điều này xảy ra, thiết bị đã đạt đến trạng thái phân trang bộ nhớ, vì vậy, thao tác này là bắt buộc để duy trì khả năng phản hồi của giao diện người dùng.
- Quy trình hiển thị đang thực hiện công việc mà người dùng hiện đang biết, vì vậy, việc loại bỏ quy trình này sẽ ảnh hưởng tiêu cực đáng kể đến trải nghiệm người dùng. Một quy trình được coi là hiển thị trong các điều kiện sau:
- Ứng dụng này đang chạy một
Activity
mà người dùng có thể nhìn thấy trên màn hình nhưng không phải ở nền trước (phương thức onPause()
của ứng dụng đã được gọi). Điều này có thể xảy ra, ví dụ: nếu Activity
ở nền trước hiển thị dưới dạng hộp thoại cho phép Activity
trước đó xuất hiện phía sau.
- Ứng dụng này có một
Service
đang chạy dưới dạng dịch vụ trên nền trước, thông qua Service.startForeground()
(yêu cầu hệ thống coi dịch vụ này là một dịch vụ mà người dùng biết hoặc về cơ bản là như thể dịch vụ này hiển thị).
- Ứng dụng này đang lưu trữ một dịch vụ mà hệ thống đang sử dụng cho một tính năng cụ thể mà người dùng biết, chẳng hạn như hình nền động hoặc dịch vụ phương thức nhập.
Số lượng các quy trình này chạy trong hệ thống ít bị ràng buộc hơn so với các quy trình trên nền trước, nhưng vẫn được kiểm soát tương đối. Các quy trình này được coi là cực kỳ quan trọng và không bị loại bỏ trừ phi cần thiết để duy trì tất cả các quy trình trên nền trước.
- Quy trình dịch vụ là quy trình chứa một
Service
đã được bắt đầu bằng phương thức startService()
. Mặc dù người dùng không thể trực tiếp nhìn thấy các quy trình này, nhưng chúng thường thực hiện những việc mà người dùng quan tâm (chẳng hạn như tải lên hoặc tải xuống dữ liệu mạng ở chế độ nền), vì vậy, hệ thống luôn duy trì các quy trình như vậy đang chạy trừ khi không có đủ bộ nhớ để giữ lại tất cả các quy trình hiển thị và trên nền trước.
Các dịch vụ đã chạy trong thời gian dài (chẳng hạn như 30 phút trở lên) có thể bị giảm mức độ quan trọng để quá trình của chúng chuyển sang danh sách được lưu vào bộ nhớ đệm.
Bạn có thể tạo các quy trình cần chạy trong một thời gian dài bằng setForeground
.
Nếu đó là một quy trình định kỳ yêu cầu thời gian thực thi nghiêm ngặt, thì bạn có thể lên lịch cho quy trình đó thông qua AlarmManager
.
Để biết thêm thông tin, hãy tham khảo phần Hỗ trợ trình thực thi chạy trong thời gian dài.
Điều này giúp tránh các tình huống mà các dịch vụ chạy trong thời gian dài sử dụng quá nhiều tài nguyên, chẳng hạn như rò rỉ bộ nhớ, khiến hệ thống không thể mang lại trải nghiệm tốt cho người dùng.
- Quy trình lưu vào bộ nhớ đệm là quy trình hiện không cần thiết, vì vậy, hệ thống có thể xoá quy trình đó khi cần khi các tài nguyên như bộ nhớ cần được sử dụng ở nơi khác. Trong một hệ thống hoạt động bình thường, đây là những quy trình duy nhất liên quan đến việc quản lý tài nguyên.
Một hệ thống hoạt động tốt luôn có nhiều quy trình được lưu vào bộ nhớ đệm để chuyển đổi hiệu quả giữa các ứng dụng và thường xuyên đóng các ứng dụng đã lưu vào bộ nhớ đệm khi cần.
Chỉ trong những trường hợp rất nghiêm trọng, hệ thống mới đến một điểm mà tất cả các quy trình lưu vào bộ nhớ đệm đều bị tắt và hệ thống phải bắt đầu tắt các quy trình dịch vụ.
Vì hệ thống có thể huỷ các quy trình lưu vào bộ nhớ đệm bất cứ lúc nào, nên các ứng dụng phải ngừng mọi hoạt động khi ở trạng thái lưu vào bộ nhớ đệm. Nếu ứng dụng phải thực hiện công việc quan trọng đối với người dùng, thì ứng dụng đó phải sử dụng một trong các API trên để chạy công việc từ trạng thái quy trình đang hoạt động.
Các quy trình lưu vào bộ nhớ đệm thường giữ một hoặc nhiều thực thể Activity
mà người dùng hiện không nhìn thấy (phương thức onStop()
của các thực thể này đã được gọi và trả về).
Miễn là họ triển khai vòng đời Activity
đúng cách khi hệ thống huỷ các quy trình như vậy, thì điều này sẽ không ảnh hưởng đến trải nghiệm của người dùng khi quay lại ứng dụng đó. Vòng đời có thể khôi phục trạng thái đã lưu trước đó khi hoạt động liên kết được tạo lại trong một quy trình mới. Xin lưu ý rằng onDestroy()
không được đảm bảo sẽ được gọi trong trường hợp hệ thống chấm dứt một quy trình.
Để biết thêm thông tin, hãy xem Activity
.
Kể từ Android 13, một quy trình ứng dụng có thể nhận được thời gian thực thi có giới hạn hoặc không có thời gian thực thi cho đến khi quy trình đó chuyển sang một trong các trạng thái vòng đời đang hoạt động ở trên.
Các quy trình được lưu vào bộ nhớ đệm được lưu giữ trong một danh sách. Chính sách sắp xếp chính xác cho danh sách này là thông tin triển khai chi tiết của nền tảng. Nhìn chung, trình quản lý này cố gắng giữ lại các quy trình hữu ích hơn, chẳng hạn như các quy trình lưu trữ ứng dụng trên màn hình chính của người dùng hoặc hoạt động gần đây nhất mà người dùng đã xem, trước các loại quy trình khác. Bạn cũng có thể áp dụng các chính sách khác để loại bỏ các quy trình, chẳng hạn như đặt giới hạn cứng về số lượng quy trình được phép hoặc giới hạn thời lượng một quy trình có thể liên tục lưu vào bộ nhớ đệm.
Khi quyết định cách phân loại một quy trình, hệ thống sẽ dựa vào cấp độ quan trọng nhất trong số tất cả các thành phần hiện đang hoạt động trong quy trình đó.
Hãy xem tài liệu về Activity
, Service
và BroadcastReceiver
để biết thêm thông tin chi tiết về cách mỗi thành phần này đóng góp vào vòng đời tổng thể của một quy trình và của ứng dụng.
Mức độ ưu tiên của một quy trình cũng có thể tăng lên dựa trên các phần phụ thuộc khác mà quy trình đó có. Ví dụ: nếu quy trình A đã liên kết với Service
bằng cờ Context.BIND_AUTO_CREATE
hoặc đang sử dụng ContentProvider
trong quy trình B, thì việc phân loại quy trình B ít nhất cũng quan trọng như quy trình A.
Nội dung và mã mẫu trên trang này phải tuân thủ các giấy phép như mô tả trong phần Giấy phép nội dung. Java và OpenJDK là nhãn hiệu hoặc nhãn hiệu đã đăng ký của Oracle và/hoặc đơn vị liên kết của Oracle.
Cập nhật lần gần đây nhất: 2025-07-27 UTC.
[[["Dễ hiểu","easyToUnderstand","thumb-up"],["Giúp tôi giải quyết được vấn đề","solvedMyProblem","thumb-up"],["Khác","otherUp","thumb-up"]],[["Thiếu thông tin tôi cần","missingTheInformationINeed","thumb-down"],["Quá phức tạp/quá nhiều bước","tooComplicatedTooManySteps","thumb-down"],["Đã lỗi thời","outOfDate","thumb-down"],["Vấn đề về bản dịch","translationIssue","thumb-down"],["Vấn đề về mẫu/mã","samplesCodeIssue","thumb-down"],["Khác","otherDown","thumb-down"]],["Cập nhật lần gần đây nhất: 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."]]