Earlier, I answered a question on Zhihu: How do I keep Android apps running in the background and not being killed like QQ? . On the Android platform process survival, must be one of the Android developers attention. If you search the Internet for Android process preservation, you’ll find all sorts of wacky ways to do it, most of them downright wacky. A while ago, Github also created a very popular “hack technology” process repository that claims to make processes immortal.

I went to Github to look around in the mood of learning and worship, only to find that many people made an Issue saying that all kinds of machines could not survive successfully.

When I saw this, I was instantly relieved. To be honest, I really don’t want this kind of hacking technology to exist, it just breeds more rogue apps and drags down the smoothness of my Android platform.

Having pulled so much, next we will directly enter the main topic of this article, talk about the knowledge of process survival. Make the following four statements in advance

  • This article is my Android development so far comprehensive information obtained
  • Not to save energy to maintain the process of survival means, are playing rogue
  • This article is not intended to teach you how to make immortal processes. If you expect the implementation process to be immortal, please ignore this article
  • If there are any mistakes in this article, please leave a comment to discuss them.

Keep alive means

Currently, the industry’s Android process survival means are mainly divided into black, white, gray three, its general implementation ideas are as follows:

Black: Different APP processes wake up each other with broadcasts (including system-provided broadcasts)

White: Start foreground Service

Grey Protection: Start foreground Service using system vulnerability

Black keep alive

The so-called black survival is the use of different APP processes using broadcast to wake up each other. Here are three common scenarios:

Scenario 1: Wake up the APP with the broadcast generated by the system during startup, network switching, photo taking, and video shooting

Scenario 2: Accessing a third-party SDK will also wake up the corresponding APP process. For example, the wechat SDK will wake up wechat, and the Alipay SDK will wake up Alipay. Spreading out from this will directly trigger scenario 3 below

Scenario 3: If you have Alipay, Taobao, Tmall, UC and other Alibaba apps installed in your mobile phone, you may wake up other Alibaba apps after opening any of them. (Just take Ali as an example, in fact, BAT is similar)

That’s right, our Android phones are being towed step by step by step.

For scenario 1, Google is probably starting to realize these issues, so in the latest Android N, ACTION_NEW_PICTURE, ACTION_NEW_VIDEO, CONNECTIVITY_ACTION (network switching) and other three broadcasts, undoubtedly gave a lot of apps a heavy blow. I guess their mood goes something like this

And boot broadcast, remember some custom ROM manufacturers have already removed it.

For scenario 2 and scenario 3, invoking the SDK to wake up the APP process is a normal behavior and is not discussed here. However, when analyzing the wake path between apps with the help of LBE, two problems were found:

  1. Many push SDKS also have the ability to wake up the app
  2. The wake up paths between apps are numerous and complex

I will show you the test results of my mobile phone (my mobile phone is mi 4C, which is running the native Android5.1 system, and I have obtained Root permission to view these wake paths).

15 groups wake up each other

Full wake up path

Let’s go straight to the wake up path of the brief book

Simple book wake up path

You can see the above three wake up paths, but the total number of wake up apps covered is 23+43+28, which is amazing. Please note that this is just the wake up path of an app on my phone.

Of course, there is still a question, is the LBE analysis of the application of these wake paths and mutual wake, we do not know the thinking. Therefore, we are not sure whether the analysis results are accurate. If some LBE children read this article, could you please tell us your thoughts? However, the mobile phone opens an APP to wake up a large number of, but I personally experience this acid cool……

White keep alive

The white preservation method is very simple. It is to call the system API to start a foreground Service process, which will generate a Notification in the Notification bar of the system to let users know that such an app is running, even if the current APP has retreated to the background. LBE and QQ Music are as follows:

Gray keep alive

Gray preservation, this means of preservation is the most widely used. It takes advantage of system vulnerabilities to start a foreground Service process. The difference with the common startup mode is that it does not show a Notification in the system Notification bar, and looks like running a background Service process. The advantage of this is that the user will not know that you are running a foreground process (because the Notification cannot be seen), but your process has a higher priority than a normal background process. Then how to use the system vulnerabilities, the general implementation ideas and codes are as follows:

  • New Notification() is passed to the foreground Service when API < 18.
  • API >= 18, start two foreground services with the same ID, and then stop the last Service.
public class GrayService extends Service { private final static int GRAY_SERVICE_ID = 1001; @Override public int onStartCommand(Intent intent, int flags, int startId) { if (Build.VERSION.SDK_INT < 18) { startForeground(GRAY_SERVICE_ID, new Notification()); Else {Intent innerIntent = new Intent(this, grayinnerservice.class); startService(innerIntent); startForeground(GRAY_SERVICE_ID, new Notification()); } return super.onStartCommand(intent, flags, startId); }... . GrayInnerService extends Service {@override public int GrayInnerService extends Service {@override public int GrayInnerService extends Service {@override public int onStartCommand(Intent intent, int flags, int startId) { startForeground(GRAY_SERVICE_ID, new Notification()); stopForeground(true); stopSelf(); return super.onStartCommand(intent, flags, startId); }}}Copy the code

This is basically the code that allows you to start a foreground Service without anyone noticing. In fact, many apps in the market use this kind of grey survival method. What? You don’t believe? All right, let’s test that. The process is simple. Open an app and check whether there is a Notification in the system Notification bar. If not, enter the ADB shell mode of the phone and enter the following shell command

dumpsys activity services PackageName
Copy the code

Print Service information about all processes whose package name is specified. Check whether isForeground=true is the key information. If the Notification belonging to app is not found in the Notification bar and isForeground=true is displayed, it indicates that the app uses this method of grey preservation.

Below are the test results of wechat, QQ, Alipay and Momo on my mobile phone. If you are interested, you can verify it yourself.

WeChat

Hand Q

Alipay

Momo

In fact, Google is aware of the existence of this vulnerability, and gradually closed. This is why there are two cases of API >= 18 and API < 18. From the postNotification function source code of the ServiceRecord class on Android5.0, you can see this line of comment

One day when API >= 18 doesn’t work, we have to find another way out. Note that using grey save does not mean your Service is immortal, only that it increases the priority of the process. If your app process consumes a lot of memory, reclaiming the process will also kill your app. Keep alive is interested in gray not showing how to use the system vulnerabilities Notification of children’s shoes, you can study the system’s ServiceRecord, NotificationManagerService related source code, because is not the focus of this article, so do not elaborate.

Nagging dividing line

Here is basically the introduction of black, white, gray three implementation methods, only from the code level to talk about the survival is not enough, I hope to understand the survival through the system process recycling mechanism, so that we can better avoid stepping on the pit of process killing.

Process reclaiming mechanism

If you are familiar with the Android system, you will know that the system does not actually kill the process when the app goes back to the background, but cache it for the sake of experience and performance. The more applications open, the more processes are cached in the background. When the system memory is insufficient, the system starts to determine which processes to kill according to its own process reclaiming mechanism, so as to free up memory for the needed app. This mechanism is called Low Memory Killer, which is based on OOM Killer (out-of-memory Killer) mechanism Of Linux kernel.

Low Memory Killer Low Memory Killer What is oom_adj? It is a value assigned by the Linux kernel to each system process. It represents the priority of the process, and the process reclamation mechanism determines whether to recycle based on this priority. Here’s what you need to remember about what oOM_adj does:

  • The larger the oOM_adj value is, the lower the priority is and the easier the process is to be killed and reclaimed. The smaller the value is, the higher the process priority is and the harder it is to kill and recycle
  • <0< strong=””>

How do we check the oOM_adj value of a process using the following two shell commands

Ps | grep PackageName / / for you specify the process of informationCopy the code
! [](http://upload-images.jianshu.io/upload_images/912181-5a244b4256260e76.jpg?imageMogr2/auto-orient/strip%7CimageView2/2 /w/1240)

Here is the demo code I wrote as an example, the middle of the red circle are the ids of the following three processes

UI process: com.clock.daemon Common background process: com.clock.daemon:bg Grey preservation process: com.clock.daemon:gray

Of course, the ids of these processes are also available from AndroidStudio

And then let’s get three more processesoom_adj Cat /proc/process ID/oom_adj

As you can see from the figure above, the OOM_adj of the UI process and the grey preservation Service process is 0, while the oom_adj of the normal background process is 15. You can see why background processes are easier to recycle than foreground processes. But that’s not enough. Look at the picture below

If I switch the app to the background and check oOM_adj again, you can see that the UI process has changed from 0 to 6, and the grey Service process has changed from 0 to 1. Here you can see that when the app goes back into the background, all of its processes take a lower priority. But the UI process is the most obvious reduction, because it occupies the most memory resources, when the system is running out of memory must be prioritized to kill these processes to free up resources. Therefore, in order to avoid killing the background UI process, it is necessary to release some unused resources as much as possible, especially images, audio and video.

From the Official Android documentation, we can also see the different types of processes listed in order of priority: Foreground Process, Visible Process, Service Process, Background process, Empty process. What are the oOM_adj of these processes and how are they linked? I recommend reading the following article:

www.cnblogs.com/angeldevil/…

Summary (With benefits at the end)

Having written so much of the ramble, I would like to conclude with a little. Going back to the question of QQ’s immortality, I thought there was such a technology. Unfortunately, I put the phone root, kill the QQ process will never get up. Some phone manufacturers have whitelisted these well-known apps to improve user experience by keeping the process immortal (wechat, QQ and Momo are all on Xiaomi’s whitelist). If they are removed from the whitelist, they will eventually be killed just like ordinary apps. In order to avoid being killed, it is better to do a good job of optimization.

Therefore, the fundamental solution to process survival comes back to performance optimization after all, and process immortality is a completely false proposition after all!

This article ends, the relevant simple practice code see

Github.com/D-clock/And…

In order to thank the children who read this article, I specially present a picture of welfare… Please note:

If you have someone next to you, please watch !!!!!!!!! carefully

If you have someone next to you, please watch !!!!!!!!! carefully

If you have someone next to you, please watch !!!!!!!!! carefully

welfare