Proses dan siklus hidup aplikasi
Tetap teratur dengan koleksi
Simpan dan kategorikan konten berdasarkan preferensi Anda.
Biasanya, setiap aplikasi Android berjalan dalam proses Linux-nya sendiri.
Proses ini dibuat untuk aplikasi jika beberapa kodenya harus
berjalan dan tetap berjalan hingga sistem perlu mendapatkan kembali memorinya untuk digunakan
oleh aplikasi lain dan tidak lagi diperlukan.
Fitur yang tidak biasa dan mendasar dari Android adalah bahwa masa aktif proses aplikasi
tidak dikontrol langsung oleh aplikasi itu sendiri.
Sebaliknya, hal ini ditentukan oleh sistem melalui kombinasi beberapa bagian aplikasi
yang diketahui oleh sistem sedang berjalan, seberapa penting hal-hal tersebut bagi pengguna,
dan seberapa banyak memori keseluruhan yang tersedia dalam sistem.
Penting bagi
developer aplikasi untuk memahami bagaimana komponen aplikasi yang berbeda
(khususnya Activity
, Service
,
dan BroadcastReceiver
) memengaruhi masa aktif
proses aplikasi. Tidak menggunakan komponen ini dengan benar dapat menyebabkan sistem menghentikan proses aplikasi saat sedang melakukan pekerjaan penting.
Contoh umum bug siklus proses adalah
BroadcastReceiver
yang memulai thread saat
menerima Intent
dalam metode
BroadcastReceiver.onReceive()
-nya, lalu kembali dari fungsi. Setelah kembali, sistem
akan menganggap BroadcastReceiver
tidak lagi aktif, dan proses
hostingnya tidak lagi diperlukan, kecuali jika komponen aplikasi lainnya aktif di
dalamnya.
Jadi, sistem dapat mengakhiri proses kapan saja untuk mendapatkan kembali memori, dan dengan melakukannya,
sistem akan menghentikan thread yang sedang berjalan dalam proses tersebut. Solusi untuk masalah ini
biasanya adalah menjadwalkan JobService
dari BroadcastReceiver
sehingga
sistem mengetahui bahwa ada pekerjaan aktif yang terjadi dalam proses tersebut.
Untuk menentukan proses mana yang akan dihentikan saat memori hampir habis, Android
menempatkan setiap proses ke dalam hierarki kepentingan berdasarkan komponen yang berjalan di
dalamnya dan status komponen tersebut. Menurut urutan kepentingannya, jenis proses ini adalah:
- Proses latar depan adalah proses yang diperlukan untuk
hal yang sedang dilakukan pengguna. Berbagai komponen aplikasi dapat
menyebabkan proses di dalamnya dianggap sebagai latar depan dengan cara yang
berbeda. Proses dianggap berada di latar depan jika salah satu
kondisi berikut terpenuhi:
Hanya ada beberapa proses seperti itu di dalam sistem, dan proses tersebut hanya
dihentikan sebagai upaya terakhir jika memori terlalu sedikit sehingga proses ini tidak dapat terus berjalan. Umumnya, jika hal ini terjadi, perangkat telah
mencapai status paging memori, sehingga tindakan ini diperlukan untuk menjaga antarmuka
pengguna tetap responsif.
- Proses yang terlihat melakukan pekerjaan yang saat ini diketahui oleh pengguna,
sehingga mengakhiri proses tersebut akan memiliki dampak negatif yang nyata terhadap pengalaman pengguna. Proses dianggap
terlihat dalam kondisi berikut:
- Proses menjalankan
Activity
yang dapat dilihat oleh pengguna di layar, tetapi tidak di latar depan (metode
onPause()
-nya
telah dipanggil). Hal ini mungkin
terjadi, misalnya, jika Activity
latar depan ditampilkan sebagai dialog
yang memungkinkan Activity
sebelumnya terlihat di belakangnya.
- Proses memiliki
Service
yang berjalan sebagai layanan latar depan,
melalui Service.startForeground()
(yang
meminta sistem memperlakukan layanan sebagai sesuatu yang diketahui pengguna, atau pada dasarnya
seolah-olah terlihat).
- Layanan ini menghosting layanan yang digunakan sistem untuk fitur tertentu yang
diketahui pengguna, seperti wallpaper animasi atau layanan metode input.
Jumlah proses yang berjalan pada sistem ini kurang dibatasi daripada proses
latar depan, tetapi masih relatif terkendali. Proses ini
dianggap sangat penting dan tidak dihentikan kecuali jika
diperlukan untuk menjaga semua proses latar depan tetap berjalan.
- Proses layanan adalah proses yang menyimpan
Service
yang telah dimulai dengan
metode startService()
. Meskipun proses
ini tidak langsung terlihat oleh pengguna, proses tersebut umumnya melakukan hal-hal
yang penting bagi pengguna (seperti upload atau download
data jaringan latar belakang), sehingga sistem selalu membuat proses tersebut
berjalan kecuali jika tidak ada cukup memori untuk mempertahankan semua proses latar depan dan yang terlihat.
Layanan yang telah berjalan lama (misalnya, 30 menit atau lebih) mungkin
didemosikan menjadi penting agar prosesnya dapat diteruskan ke daftar yang di-cache.
Proses yang perlu dijalankan dalam jangka waktu lama dapat dibuat dengan
setForeground
.
Jika merupakan proses berkala yang memerlukan waktu eksekusi yang ketat, proses tersebut dapat
dijadwalkan melalui AlarmManager
.
Untuk informasi selengkapnya, lihat Dukungan untuk pekerja yang berjalan lama.
Hal ini membantu menghindari situasi saat layanan yang berjalan lama yang menggunakan resource yang berlebihan, misalnya, dengan kebocoran memori, mencegah sistem memberikan pengalaman pengguna yang baik.
- Proses yang tersimpan di dalam cache adalah salah satu yang saat ini tidak diperlukan, sehingga
sistem bebas untuk menghentikannya kapan saja saat resource seperti memori diperlukan di tempat lain. Dalam sistem yang berperilaku
normal, proses ini adalah satu-satunya proses yang terlibat dalam pengelolaan resource.
Sistem yang berjalan dengan baik memiliki beberapa proses cache yang selalu tersedia, untuk peralihan
yang efisien antar-aplikasi, dan secara teratur menghentikan aplikasi yang di-cache sesuai kebutuhan.
Hanya dalam situasi yang sangat kritis, sistem akan sampai pada tahap di mana
semua proses yang disimpan dalam cache akan dihentikan dan harus mulai mengakhiri proses layanan.
Karena proses yang di-cache dapat dihentikan oleh sistem kapan saja, aplikasi harus menghentikan semua pekerjaan saat
dalam status di-cache. Jika pekerjaan penting bagi pengguna harus dilakukan oleh aplikasi,
aplikasi harus menggunakan salah satu API di atas untuk menjalankan pekerjaan dari status proses aktif.
Proses yang di-cache sering kali menyimpan satu atau beberapa instance Activity
yang saat ini tidak terlihat oleh pengguna (metode
onStop()
-nya telah dipanggil dan ditampilkan).
Selama siklus proses Activity
diterapkan dengan benar saat sistem
menghentikan proses tersebut, hal ini tidak akan memengaruhi pengalaman pengguna saat kembali ke aplikasi tersebut.
Aplikasi dapat memulihkan status yang disimpan sebelumnya saat aktivitas terkait dibuat ulang dalam
proses baru. Perhatikan bahwa onDestroy()
tidak dijamin akan dipanggil jika proses dihentikan oleh sistem.
Untuk detail selengkapnya, lihat Activity
.
Mulai Android 13, proses aplikasi mungkin menerima waktu eksekusi terbatas atau tidak ada hingga memasuki
salah satu status siklus proses aktif di atas.
Proses yang di-cache disimpan dalam daftar. Kebijakan pengurutan yang tepat untuk daftar ini
adalah detail implementasi platform. Umumnya, sistem ini mencoba mempertahankan proses yang lebih berguna, seperti yang menghosting aplikasi beranda pengguna atau aktivitas terakhir yang dilihat pengguna, sebelum jenis proses lainnya. Kebijakan lain untuk menghentikan proses juga dapat
diterapkan, seperti menetapkan batas penggunaan pada jumlah proses yang diizinkan atau membatasi jumlah
waktu proses dapat terus-menerus disimpan di dalam cache.
Saat memutuskan cara mengklasifikasikan proses, sistem mendasarkan keputusannya pada tingkat yang paling penting yang ditemukan di antara semua komponen yang saat ini aktif dalam proses.
Lihat dokumentasi Activity
, Service
, dan
BroadcastReceiver
untuk mengetahui detail selengkapnya tentang cara
setiap komponen ini berkontribusi pada keseluruhan siklus proses dan
aplikasi.
Prioritas proses juga dapat ditingkatkan berdasarkan dependensi lain
yang dimiliki proses tersebut. Misalnya, jika proses A terikat pada
Service
dengan
flag Context.BIND_AUTO_CREATE
atau menggunakan
ContentProvider
dalam proses B, maka klasifikasi
proses B akan selalu setidaknya sama pentingnya dengan proses A.
Konten dan contoh kode di halaman ini tunduk kepada lisensi yang dijelaskan dalam Lisensi Konten. Java dan OpenJDK adalah merek dagang atau merek dagang terdaftar dari Oracle dan/atau afiliasinya.
Terakhir diperbarui pada 2025-07-27 UTC.
[[["Mudah dipahami","easyToUnderstand","thumb-up"],["Memecahkan masalah saya","solvedMyProblem","thumb-up"],["Lainnya","otherUp","thumb-up"]],[["Informasi yang saya butuhkan tidak ada","missingTheInformationINeed","thumb-down"],["Terlalu rumit/langkahnya terlalu banyak","tooComplicatedTooManySteps","thumb-down"],["Sudah usang","outOfDate","thumb-down"],["Masalah terjemahan","translationIssue","thumb-down"],["Masalah kode / contoh","samplesCodeIssue","thumb-down"],["Lainnya","otherDown","thumb-down"]],["Terakhir diperbarui pada 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."]]