Heavy leaks! Encyclopedia of Tencent Android process keep-alive moves out! (Quick look)

Preface

The process of keeping alive has always been the boss's favorite black technology. After learning it, you can pretend to be forced in front of the boss. Learn fast!

At present, applications on the market, except WeChat and Mobile QQ, seem to be more worried about being killed by users or systems (vendors). This article summarizes Tencent's Android process.

Android process pull live includes two levels:

A. Provide process priority to reduce the probability of process being killed

B. After the process is killed, pull live

This article summarizes these two aspects below.

1. The priority of the process

The Android system will keep the application process as long as possible, but in order to create a new process or run a more important process, it will eventually need to clear the old process to reclaim the memory. In order to determine which processes to keep or terminate, the system puts each process into an "importance hierarchy" based on the components that are running in the process and the state of these components. When necessary, the system will first eliminate the least important process, then remove the less important process, and so on, to reclaim system resources.

The importance of the process is divided into 5 levels:

  1. Foreground process

  2. Visible process

  3. Service process

  4. Background process

  5. Empty process

The importance of the foreground process is the highest, and the importance of the empty process is the lowest. The process of each level is explained below.

1.1. Foreground process-Foreground process

The process necessary for the user's current operation. Usually there are not many foreground processes at any given time. The system will only terminate them if there is not enough memory to support them while continuing to run as a last resort.

A. Own the Activity that the user is interacting with (onResume() has been called)

B. Own a Service, which is bound to the Activity that the user is interacting with

C. Have a Service running in the "foreground" (the service has called startForeground())

D. Have a Service (onCreate(), onStart() or onDestroy()) that is executing a lifecycle callback

E. Have a BroadcastReceiver that is executing its onReceive() method

1.2. Visible process-Visible process

There is no foreground component, but it still affects the progress of what the user sees on the screen. Visible processes are regarded as extremely important processes, and the system will not terminate these processes unless they must be terminated in order to maintain all foreground processes running at the same time.

A. Have an Activity that is not in the foreground but is still visible to the user (onPause() has been called).

B. Have a Service bound to the visible (or foreground) Activity

1.3. Service process-Service process

Although service processes are not directly related to what the user sees, they are usually performing operations that the user cares about (for example, playing music in the background or downloading data from the network). Therefore, unless the memory is not enough to maintain all foreground and visible processes running at the same time, the system will keep the service process running.

A. The service started by the startService() method is running, and is not a process of the above two higher-class processes.

1.4. Background process-Background process

Background processes have no direct impact on user experience, and the system may terminate them at any time to reclaim memory for use by foreground processes, visible processes, or service processes. There are usually many background processes running, so they will be saved in the LRU list to ensure that the process containing the most recently viewed activity by the user is terminated last. If an Activity correctly implements the life cycle method and saves its current state, terminating its process will not have a significant impact on the user experience, because when the user navigates back to the Activity, the Activity will restore all its visible states.

A. The process of Activity that is not visible to the user (Activity's onStop() method has been called)

1.5. Empty process-Empty process

The only purpose of keeping this kind of process is to be used as a cache to shorten the startup time required to run the component in it next time. In order to balance the overall system resources between the process cache and the underlying kernel cache, the system often terminates these processes.

A. Process without any active application components

For details, please refer to: http://developer.android.com/intl/zh-cn/guide/components/processes-and-threads.html

2. Android process recycling strategy

The recycling of memory in Android mainly relies on Lowmemorykiller, which is a mechanism that triggers the corresponding intensity of memory recycling based on the OOM_ADJ threshold level.

The description of OOM_ADJ is as follows:

The red part represents Android processes that are easier to kill (OOM_ADJ>=4), the green part represents Android processes that are not easily killed, and the others represent non-Android processes (pure Linux processes). When Lowmemorykiller reclaims memory, it will kill processes with a larger OOM_ADJ first according to the level of the process. For processes with the same priority, it is further affected by the memory occupied by the process and the survival time of the process.

The process of being killed in an Android phone may have the following situations:

In summary, it can be concluded that reducing the probability of a process being killed is nothing more than finding ways to increase the priority of the process, and reducing the probability of a process being killed in situations such as insufficient memory.

3. Scheme to increase the priority of the process

3.1. Use Activity to escalate permissions

3.1.1. Scheme design ideas

Monitor mobile phone lock screen unlock events, start a 1-pixel activity when the screen is locked, and destroy the activity when the user unlocks it. Note that the Activity needs to be designed so that the user does not perceive.

Through this scheme, the priority of the process can be raised from 4 to the highest priority 1 during the screen lock time.

3.1.2. The scope of application of the program

Applicable scenarios: This solution mainly solves the problem that third-party applications and system management tools will kill the background process within a period of time (usually within 5 minutes) after detecting the lock screen event, which has achieved the purpose of saving power.

Applicable version: Applicable to all Android versions.

3.1.3. The concrete realization of the scheme

First define the Activity and set the size of the Activity to 1 pixel:

Second, use the following attributes from AndroidManifest to exclude Activity from being displayed in RecentTask:

Finally, control the Activity to be transparent:

Control of the timing of Activity start and destruction:

3.2. Use Notification to elevate permissions

3.2.1. Scheme design ideas

The priority of Service in Android is 4, and the background service can be set to the foreground service through the setForeground interface, so that the priority of the process is increased from 4 to 2, so that the priority of the process is only lower than the process that the user is currently interacting with. The process priority is the same, so that the probability of the process being killed is greatly reduced.

3.2.2. Challenges of solution realization

When calling setForeground from Android 2.3 to set the background service as the foreground service, a notification must be sent in the notification bar of the system, that is, the foreground service is bound to a visible notification.

For applications that do not require a permanent notification bar, this solution is good, but it is user-perceived and cannot be used directly.

3.2.3. Measures to address the challenges of the program

By implementing an internal Service, a Notification with the same ID is sent in the LiveService and its internal Service at the same time, and then the internal Service is terminated. With the end of the internal Service, Notification will disappear, but the system priority remains at 2.

3.2.4. The scope of application of the program

Applicable to all currently known versions.

3.2.5. The concrete realization of the scheme

4. The plan to pull the process alive after death

4.1. Use system broadcast to pull live

4.1.1. Scheme design ideas

When a specific system event occurs, the system will send out a response broadcast. By "statically" registering the corresponding broadcast listener in the AndroidManifest, it can be activated when a response event occurs.

Commonly used broadcast events for pulling live include:

4.1.2. The scope of application of the program

Applicable to all Android platforms. But there are several shortcomings as follows:

1) Scenes where the broadcast receiver is disabled by management software and system software through functions such as "self-start management" cannot receive broadcasts, and thus cannot be self-started.

2) The system broadcast event is not controllable, and it can only ensure that the process is activated when the event occurs, but it cannot be guaranteed that the process will be activated immediately after it hangs.

Therefore, this program is mainly used as a backup method.

4.2. Use third-party applications to broadcast live

4.2.1. Scheme design ideas

The overall design idea of ​​this program is similar to that of receiving system broadcasts, but the difference is that this program is for receiving third-party Top application broadcasts.

By decompiling third-party Top applications, such as mobile QQ, WeChat, Alipay, UC browser, etc., as well as SDKs such as Youmeng, Homing Pigeon, and Twitter, find out their outgoing broadcasts and monitor them in the application. When the application broadcasts, it will bring our application to life.

4.2.2. The scope of application of the scheme

In addition to the same factors as system broadcasting, the effectiveness of the program is mainly limited by the following factors:

1) How many third-party applications have been decompiled and analyzed

2) The broadcast of third-party applications is private to the application, and the broadcasts that are valid in the current version may be removed or changed to not broadcast at any time in subsequent versions.

These factors have affected the effect of pulling live.

4.3. Use the system Service mechanism to pull live

4.3.1. Scheme design ideas

Set the Service to START_STICKY, and use the system mechanism to automatically activate the service after it hangs up:

4.3.2. The scope of application of the program

Unable to pull live in the following two situations:

  1. The Service will restart within 5 seconds after being abnormally killed for the first time, within 10 seconds for the second time, and within 20 seconds for the third time. Once the Service is killed within a short period of time, it will restart within 5 seconds. Times, the system will no longer be pulled up.

  2. The process is stopped by the management tool or system tool with root permission through forestop and cannot be restarted.

4.4. Use the Native process to pull live

4.4.1. Scheme design ideas

**Main idea: **Use the fork mechanism in Linux to create a Native process, monitor the survival of the main process in the Native process, and immediately pull the main process alive in the Native process when the main process hangs.

**Main principle: **The life cycle of all processes and system components in Android is managed uniformly by ActivityManagerService. Moreover, the process created by Linux's fork mechanism is a pure Linux process, and its life cycle is not managed by Android.

4.4.2. The challenge of solution realization

Challenge 1: How to perceive the death of the main process in the Native process.

There are two ways to realize whether the main process is alive in the Native process:

  1. In the Native process, through an endless loop or timer, it is determined whether the main process is alive through round-robin training, and when the main process is not alive, it is pulled live. The big disadvantage of this scheme is that it constantly polls to execute the judgment logic, which consumes a lot of power.

  2. Create a monitoring file in the main process, and hold a file lock in the main process. After the pull live process is started, the file lock application will be blocked. Once the lock can be successfully obtained, it means that the main process is hung up and the pull live can be performed. Since the applications in Android are all running on the virtual machine, the file lock of the Java layer is different from the file lock of the Linux layer. To achieve this function, the file lock of the Linux layer needs to be encapsulated for the upper layer to call.

The code to encapsulate the Linux file lock is as follows:

The part of the code that blocks the application file lock in the Native layer:

Challenge 2: How to activate the main process in the Native process.

Part of the code to pull the main process alive through the Native process is as follows, that is, pull it through the am command. By specifying the "-include-stopped-packages" parameter to pull the main process in the forestop state.

Challenge 3: How to ensure the uniqueness of the Native process.

Considering many aspects such as scalability and process uniqueness, the native process design layer C/S structure mode, the main process and the native process communicate through Localsocket. Use Localsocket in the Native process to ensure the uniqueness of the Native process, so that problems such as the creation of multiple Native processes and the Native process becoming a zombie process will not occur.

4.4.3. The scope of application of the program

This program is mainly suitable for mobile phones below Android5.0.

This solution is not affected by forcestop, and applications that are forced to stop can still be activated. The activation effect is very good in versions below Android 5.0.

For mobile phones above Android 5.0, although the system will kill all processes in the native process, here is actually a race between the time for the system to kill the processes "sequentially" and the execution time of the activation logic. If it can run faster than the system logic , It can still be effectively pulled up. I remember that someone has done an experiment on the Internet, the conclusion is valid, and it is valid for some Android 5.0 or higher models.

4.5. Use JobScheduler mechanism to pull live

4.5.1. Scheme design ideas

After Android5.0, the system has strengthened the management of the Native process, etc., and the Native pull method is invalid. The system provides the JobScheduler interface in Android5.0 and above, and the system will call the process regularly to make the application perform some logical operations.

In this project, I further encapsulated JobScheduler, which is compatible with versions below Android 5.0. The use of the JobScheduler interface after encapsulation is as follows:

4.5.2. The scope of application of the scheme

This program is mainly suitable for mobile phones with Android5.0 and above.

This solution is not affected by forcestop in Android5.0 and above, and applications that are forced to stop can still be activated, and the activation effect is very good in Android5.0 and above.

Only in Xiaomi mobile phones, there may be problems that sometimes cannot be pulled live.

4.6. Use account synchronization mechanism to activate

4.6.1. Scheme design ideas

The account synchronization mechanism of the Android system periodically synchronizes the accounts. The purpose of this solution is to use the synchronization mechanism to pull the process. The code for adding an account and setting the synchronization period is as follows:

This solution needs to define account authorization and synchronization services in AndroidManifest.

4.6.2. The scope of application of the program

This solution is applicable to all Android versions, including processes dropped by forestop can also be pulled live.

In the latest Android version (Android N), the system seems to have changed the account synchronization here, and this method is no longer valid.

5. Other effective pull plans

After research, it is found that there are other system activation measures that can be used, but user authorization is required during use, and the user's perception is relatively strong.

These programs include:

  1. Use system notification management authority to pull live

  2. Use auxiliary functions to pull live, and add applications to the whitelist of vendors or management software.

These solutions need to be combined with specific product characteristics.

All the above explanations of these schemes are considered non-Root situations.

There are other measures beyond the technology, such as the selection of the Push channel in the app:

  1. Foreign version application: access to Google's GCM.

  2. Domestic version of the application: According to different terminals, connect to Mi Push on Xiaomi mobile phones (including MIUI) and Huawei push on Huawei mobile phones; other mobile phones can consider connecting to Tencent Cargo Pigeon or Jiguang Push and Mi Push for A/B test.

Android learning video recommendation: Android development camel

Original address: https://zhuanlan.zhihu.com/p/21987083

At last

Android learning is a long road. What we have to learn is not only the superficial technology, but also the bottom layer and understand the following principles. Only in this way can we improve our competitiveness. In today's highly competitive world Foothold in.

As the saying goes: There are two best times to plant a tree, one is ten years ago, and the other is now.

A journey of a thousand miles begins with a single step, I hope you and I encourage each other.

My open source project: https://github.com/xieyuliang/Android-P7-share/blob/master/Android (click here to view)
contains self-learning programming routes in different directions, interview questions collection/face sutras, And a series of technical articles, etc. The resources are being continuously updated...

Welcome everyone to discuss together!

Guess you like

Origin blog.csdn.net/weixin_49559515/article/details/113351451