The Android system has its own method for memory management, in order to guarantee the orderly and stable operation of the system, the internal system will automatically allocate and control the memory usage of the program. When the system feels that the current resources are very limited, in order to ensure that some high-priority programs can run, it will kill some of the programs or services that he considers unimportant to free memory. This will ensure that programs that are really useful to the user are still running again. If your Service is in this situation, you will probably be killed first. But if you increase the priority of the service to let him stay a little more, we can use Setforeground (true) to set the service priority.
Why is foreground? The service that is started by default is marked as background, and the activity that is currently running is generally marked as foreground, which means that you set the service to foreground so that he has the same priority as the running activity. A certain increase. When this doesn't guarantee that your Service will never be killed, it just increases his priority. There is a way to give you a clearer demonstration, go to $SDK/tools Run command copy code # ADB shell Dumpsys activity|grep Oom_adj Running Norm Proc # 6:oom_adj= 0 processrecord{43635cf0 12689:com.roiding.netraffic/10028} running Norm Proc # 5:oom_adj= 7 processrecord{436feda0 12729:com.android.browser/10006} running Norm Proc # 4: oom_adj= 8 processrecord{4367e838 12761:android.process.acore/10016} running Norm Proc # 3:oom_adj= & Nbsp;8 processrecord{43691cd8 12754:com.google.process.gapps/10000} running PERS Proc # 1:oom_adj=-12 processrecord{43506750 5941:com.android.phone/1001} running PERS Proc # 0:oom_adj=-100 ProcessRecord{ 4348fde0 5908:system/1000} Copy the code back a lot of things, observe the value of Oom_adj, if it is more than 81 is the backgroud can be killed at any time, the smaller the number proves that the higher the priority, the time to killThe more late. You see the phone program is-12 that the phone is the phone, everything else is done, you can answer the phone right. There is also a-100, more damndest because it is system if he is finished, you have to hang up. I am a king of the ground Tiger Division line starting with Android 1.5, a service that has been started can call Startforeground (int, Notification) to set the service to foreground state, Call Stopforeground (Boolean) to set the service to the background state. We'll pass in the parameter Notification in the call startforeground (int, Notification), which will show the ongoing foreground service in the status bar. Background service is not displayed in the status bar. in Android 1.0, set a service to foreground status: setforeground (True); mnm.notify (ID, notification); Set a service to the background state: mnm.cancel (ID); setforeground (false); In contrast, call Setforeground (Boolean) in the 1.0 API Simply changing the status of the service, the user will not have any awareness. The new API enforces binding of notification and changing the service state, foreground service is displayed in the status bar, and background service does not. I am a king of the ground Tiger Division line through a in the Androidmanifest.xmlAdding the Android:persistent= "true" attribute to the pplication tag does ensure that the application's process is not killed by LMK. However, the premise is that the application must be a system application, that is, the application cannot use the usual installation method. The app's APK package must be placed directly under the/system/app directory. And the system must be restarted before it can take effect. In addition to the general priority, there are coreserver,system such that never be LMK recycled priority. The telephony application in the system is the coreserver priority. by looking at the source code, you can know that only the application's flag is Flag_system and flag_persistent, it is set to Coreserver priority if (info.flags& ( applicationinfo.flag_system| applicationinfo.flag_persistent) = = (Applicationinfo.flag_ system| applicationinfo.flag_persistent) { app.persistent = true; &N Bsp App.maxadj = core_server_adj; }flag_system is set when the app apk is placed under/system/app. So only setting android:persistent= "true" will still be killed in the case. tests found that when the application is put into/system/app, it will still be recognized as a normal process without rebooting the system. When the system restarts, the process starts at the beginning and sets its priority to coreserver. Through the Dumpsys activity command can clearly see the difference. Copy code running processes (most recent first): App # 3:adj= 2/1 PrOcessrecord{30858c20 1877:com.android.email/10014} (started-services) PERS # 2:adj=-100/0 ProcessRecord{ 308fb390 1713:system/1000} (fixed) App # 1:adj= 0/0 processrecord{30908198 1794:android.proces S.ACORE/10005} (top-activity) PERS # 0:adj= -12/0 processrecord{3090d488 1789:xiao.xiong.test/10026} ( Fixed) Copy code and ADJ=-12, this process will start immediately after DDMS manual stop I'm the king of the Tiger's split line and nbsp methods for a service, you can first set it to run: copy code public void in the foreground Myservice.oncreate () { super.oncreate (); Notification Notification = new Notification (Android. R.drawable.my_service_icon, "My_service_name", System.currenttimemillis ()); Pendingintent P_intent = Pendingintent.getactivity (this, 0, New Intent (this, myma Inactivity.class), 0); &nbsP Notification.setlatesteventinfo (this, "myservicenotification," Myservicenotification is running! " , p_intent); LOG.D (TAG, String.Format ("notification =%s", notification)); Startforeground (0x1982, notification); //Notification id:0x1982, you can name it as you'll.} The copy code is more privileged than the application under/data/app, for example, if the persistent property is set to True in its manifest.xml file, it can be protected from out-of-memory The impact of killer. Androidmanifest.xml files such as app ' Phone ': <application android:name= "Phoneapp" android:persistent= "true" a Ndroid:label= "@string/dialericonlabel" android:icon= "@ Drawable/ic_launcher_phone "> ... </application> After setting the app to the core level of the system, in any case will not be killed, settings->applications inside will also block the stop operation. Copy GenerationCode this before the log: proc #19: Adj=svc /b 4067b028 255:com.xxx.xxx/10001 (started-services) # CAT/ proc/255/oom_adj 4 log after Setup: pers #19: adj=core/f 406291f0 155:com.xxx.xxx/10001 (fixed) # cat/proc/155/oom_adj -12 # This is Core_server_adj Note: The Oom_adj of the INIT process is-16 (i.e. System_adj): Cat /proc/1/oom_adj Copy Code android related section analysis in file frameworks/base/services/java/com/ Android/server/am/activitymanagerservice.java has the following code: copy code final Processrecord addapplocked (ApplicationInfo Info) { Processrecord app = getprocessrecordlocked (Info.processname, Info.uid); & nbsp if (app = = null) { app = newprocessrecordlocked (null, info, NULL); nbsp Mprocessnames.put (Info.processname, Info.uid, app); & nbsp Updatelruprocesslocked (app, trUE, TRUE); } if (info.flags& (applicationinf o.flag_system| applicationinfo.flag_persistent) = = (Applicationinfo.flag_ system| applicationinfo.flag_persistent) { app.persistent = true; &N Bsp APP.MAXADJ = Core_server_adj; //This constant value is-12. } if (App.thread = = null && mpersistentstarti Ngprocesses.indexof (APP) < 0) { Mpersistentstartingprocesses.add (APP); startprocesslocked (app, "added application", App.processname); &NB Sp } return app; } copy code visible to be the core service (i.e. App.maxadj = CO Re_server_adj (-12)), application requires Flag_sysTEM and flag_persistent Two flags, Flag_system refers to the application is located under/system/app, flag_persistent refers to the persistent attribute. for frameworks/base/services/java/com/android/server/ Systemserver.java, call Activitymanagerservice.setsystemprocess (); to set its own app.maxadj to System_adj, i.e.-16. I am a king of the ground Tiger Division line The process in android is managed, and the process is automatically recycled as priority when the system process is in a tight space. This brings three questions: recycling rules: When to recycle and recycle which one? Avoid manslaughter: How to prevent it from being recycled? Data recovery and Storage: What if is recycled? Android divides the process into 6 levels, in order of priority from high to low, which in turn is the: foreground process (Foreground_app) visual process (VISIBLE_APP) secondary service process (secondary_server) background process ( Hidden_app) Content Provisioning node (content_provider) empty process (Empty_app) feature: If a process contains both service and visual activity, the process should be attributed to the visual process, Instead of the service process. In addition, if other processes depend on it, the level of a process can be improved. For example, a service in a process is bound to a component in the B process, and process A will always be considered at least as important as the B process. The phone service in the system is divided into the foreground process rather than the secondary service process. In Android, the Oom_adj value of the process also represents its priority. A higher Oom_adj value means that the process has a lower priority. The following property settings are in the file/init.rc: setprop ro. Foreground_app_adj 0 SETPROp ro. Visible_app_adj 1 SetProp ro. Secondary_server_adj 2 SetProp ro. Hidden_app_min_adj 7 SetProp ro. Content_provider_adj 14 SetProp ro. Empty_app_adj &NBSP;15/INIT.RC, the oom_ of the PID 1 process (init process) ADJ set to System_adj ( -16): # set init its forked children ' s oom_adj. write/proc/1/oom_adj–16 view native settings: cat/sys/module/lowmemorykiller/parameters/adj0,1,2,7,14,15 recovery, File/init.rc: setprop ro. Foreground_app_mem 1536 // 6M setprop ro. Visible_app_mem 2048 // &NBSP;8 m setprop ro. Secondary_server_mem 4096 // 16M setprop ro. Hidden_app_mem &NBSP; 5120 // 20M setprop ro. Content_provider_mem 5632 // 22.4M setprop ro. Empty_app_mem 6144 // 24m Some numbers are the corresponding memory thresholds, and once they are below this value, Android starts to turn off the corresponding level of progress in order. Note The units of these numbers are page:1 page = 4 KB. So the above six numbers correspond to (MB): 6,8,16,20,22,24. View current memory threshold settings: cat/sys/module/lowmemorykiller/parameters/minfree to reset the value (corresponding to different requirements): echo " 1536,2048,4096,5120,15360,23040 ">/sys/module/lowmemorykiller/parameters/minfree so that when the available memory is less than 90MB, it starts to kill the" empty process ", When the available memory is below 60MB, the "Content Provisioning node" class process starts to kill. Specific recycling implemented in Activitymanagerservice.java function trimapplications (): first removes the useless process that the package has been unloaded; updates the Oom_adj value based on the current state of the process , and then do the following: 1) Remove the process that no activity is running on, 2) If the AP has saved all activity states, End the AP. Finally, if there are still a lot of activities running, remove the activity that has been saved by the activity State. Update the value of Oom_adj: calculate the process's O in the computeoomadjlocked () of the Activitymanagerservice.java fileOm_adj, for example: if (app = = Top_app) { //The last app on the list is the Foregrou nd app. adj = foreground_app_adj; APP.AD Jtype = "Top-activity"; } I am a split line of the king's cover-up tiger &N Bsp android kernel low memory killer android in low memory Kil Ler kills the process as needed (when system memory is scarce) to free its memory, and the source code is in KERNEL/DRIVERS/MISC/LOWMEMORYKILLER.C. Simply put, it is looking for the most appropriate process to kill, freeing up the memory it occupies. The most appropriate process is: the larger the oom_adj occupies the more physical memory once a process is selected, the kernel sends a sigkill signal to kill: copy code for_each_process (p) { ...... if (selected = = NULL | | P->oomkilladj > SELECTED->OOMKILLADJ | | (P->oomkilladj = = Selected->oomkilladj && tasksize > Sel ected_tasksize) {   selected = p; } } if (Selected! = NULL ) { Force_sig (SIGKILL, selected); } Copy Code view LRU list: adb shell Dumpsys activity When Activitydemo is in the foreground: the process that contains the SERVICE has a high priority, in computeoomadjlocked it is divided into two small classes: copy code static final int Max_service_ inactivity = 30*60*1000; if (now < (s.lastactivity+max_service _inactivity) { if (adj > Secondary_server_adj) { &N Bsp adj = secondary_server_adj; &nbs P App.adjtype = "Started-services";   ; App.hidden = false;   } } if (adj > Secondary_server_adj) { & nbsp App.adjtype = "Started-bg-services"; &N Bsp It is not possible to copy the code completely so that the process is not killed, and we can make the process less likely to kill by using some actions: increase the priority of the process: * Background operation using the service in the foreground, Because a process running a service is higher than the one running the background activity; * Pressing the back key causes the activity in the process to run in the background instead of the destory, and it needs to be reloaded (without any activity in the running process being first killed). * Dependent on other high-priority processes; Force modify Process properties: * Set in Process: Setpersistent (TRUE); * Set in manifest file (as above).
Android Write a process/service that will never be killed