The application proportion of working procedure is relatively large.
For any process, we can use ADB shell PS | grep.
Its basic information
The process in Android, like feudal society, is divided into three classes and nine classes. The Android system divides the process into the following parts.
Several kinds (from high to low importance) have been summarized in detail by many great gods on the Internet (note: strictly speaking, there are six kinds).
Scene:
The 1. process contains activities that interact with users, which are in the resume.
State.
2. A process has a service that is bound to the activity that the user is interacting with.
3. A process holds a service, and the service calls the startForeground () method to make it run in the foreground.
4. A process holds a service, and the service is executing one of its life cycle callback methods, such as onCreate (), onStart () or onDestroy ().
5. A process has a BroadcastReceiver, and the BroadcastReceiver is executing its onReceive () method. Generally speaking, the program the user is using will not kill the foreground process unless the user stops the application forcibly or the system is out of memory.
Scene:
1. There is an activity that is not in the foreground but is visible to users (called onPause ()).
2. Bind the service to a visible (or foreground) activity.
The user is using it, visible and intangible. It doesn't cover the whole screen, only a part of the screen can see the progress.
If there is no foreground component, the general system will not kill the visible process unless the resources are tight.
Keep one or more foreground processes active.
event
1. A service runs in a process and is started by startService (), which is not directly related to the interface the user sees.
If there is not enough memory to keep all foreground processes and visible processes running at the same time, the service process will be terminated.
Scene:
After the user presses "Back" or "home", the program itself is invisible, but it is still running.
For example, if an Activity calls the onPause method, the system can terminate them at any time and reclaim memory.
Scene:
When a process does not contain any active components, it will be set as an empty process, which is completely useless. Killing it is good, not bad. Fuck it first!
The above is the classification of processes. How was the process strangled? For the sake of experience and performance, the app is retreating.
In the background, the system doesn't really kill the process, but caches it. The more applications are opened, the more processes are cached in the background. In the case of insufficient system memory, the system began to rely on its own process recovery mechanism.
In order to release memory to provide needed applications, it is decided which processes to kill, a mechanism to kill processes and reclaim memory.
It's called black boy with low memory. Then how to define this deficiency? This is the memory threshold that we can use.
Cat/sys/module/lowmemorykiller/parameters/minfree check the memory threshold of the mobile phone.
In fact, the system has a set of strict policies in process recycling similar to memory recycling, which can
Find out for yourself, something like this. The larger oom_adj is, the more physical memory it takes up, and it will be killed first. Ok, so now the problem of how to keep the process alive is transformed into how to reduce the value of oom_adj, for example
What makes our application occupy the least memory?
It is said that this is the process-keeping scheme of Q, and the basic idea and system generally won't kill the foreground process. So you have to
In order to make the process permanent, we only need to open one activity in the process when the screen is locked. In order to deceive users,
Let the size of this activity be 1 pixel, and be transparent without switching animation. When you open the screen, put this activity.
Shut down, so this needs to monitor the system to lock the screen broadcast. I tried it, and it really worked, as follows.
If we start an activity directly, when we press the back key to return to the desktop, the value of oom_adj is 8.
As mentioned above, in the case of insufficient resources, this process is easy to recover. Now it's built pixel by pixel.
Activities.
In order to make it more hidden, it is better to set the theme of this activity, of course, it doesn't matter.
Start LiveActivity when the screen closes and close it when the screen opens, so
Monitor system lock screen broadcast, and notify MainActivity to start or close LiveActivity in the form of interface.
Now, the main activities are changed as follows
Press back to lock the screen. Now test the value of oom_adj
Sure enough, the priority of the process has increased.
But there is still a problem, memory is also a factor to consider, the more memory, the first to kill, so put the above.
The business logic of is put in the service, and the service is opened in the MainActivity in another process.
One service is enough, so the process is lighter.
Well, through the above operations, our application will always have the same priority as the foreground process. In order to save electricity,
The system will kill the background process within a period of time after the screen lock event is detected. If this scheme is adopted, it can be avoided.
This question. But it is still possible to be killed, so I still have to be a two-way guardian. With regard to dual-process protection,
The more appropriate way is aidl, but it is not completely reliable. The principle is that when process a terminates,
B is still alive, and B can pull up process A. On the contrary, when process B is dead and A is still alive, A can pull up process B..
Pull up. Therefore, the premise of dual-process daemon is that the system can only kill processes one by one. If both processes are terminated at the same time,
This method won't work either.
in fact
Then let's take a look at the source code under Android5.0 and how ActivityManagerService is closed in the application.
Clear the memory after exiting.
After the application exits, ActivityManagerService will not only kill the main process, but also put it in.
The process group is killed together. As a result, because the child process and the main process are in the same process group, the child process is doing it and doing it.
It stopped. Therefore, the process of mobile phone application after Android5.0 is killed should adopt other schemes.
This process keep-alive scheme, which most people know, is said to have been used on WeChat and moved to the WeChat Android client.
Let's share the experience of keeping alive in the background. This scheme actually takes advantage of the loopholes in the Android foreground service.
The principle is as follows
For API level
Notice that the icon will not be displayed.
For API level > = 18: start one InnerService and two services that need priority in service a.
Start the foreground at the same time and bind the same ID. Stop the InnerService so that the notification bar icon can be displayed.
Has been deleted.
Public class KeepLiveService extension service {
public static final int NOTIFICATION _ ID = 0x 1 1; ?
Public KeepLiveService() {
}
@ Overlay
Public IBinder onBind (intent){) {
Throw a new UnsupportedOperationException ("not yet implemented");
? }
? @ Overwrite?
public void onCreate() {
? super . oncreate(); //Below //API 18, send and receive notifications directly and set them as the front desk.
If (build. VERSION. SDK _ INT< build. Version code. JELLY_BEAN_MR2){
start foreground(NOTIFICATION _ ID,new NOTIFICATION()); ?
} else {//API 18 or above. After sending a notice and setting it as the foreground, start the InnerService.
Notice. Builder builder = new notification. Builder (Ben);
builder . setsmallicon(r . MIP map . IC _ launcher);
start foreground(NOTIFICATION _ ID,builder . build());
? startService(new Intent(this,inner service . class));
? }
? }
? Public class InnerService extension service {
? @ Override public I binder on bind(Intent Intent){
? Returns null
? }?
@Override public void onCreate() {
? super . oncreate(); //Send a notification with the same ID as that in KeepLiveService, and then cancel it, canceling your foreground display.
? Notice. Builder builder = new notification. Builder (Ben);
builder . setsmallicon(r . MIP map . IC _ launcher); StartForeground (notification _ID,
builder . build());
New handler (). postDelayed(new Runnable() {?
@Override public void run() {?
stop foreground(true);
? NOTIFICATION manager manager =(NOTIFICATION manager)getsystem SERVICE(NOTIFICATION _ SERVICE);
manager . cancel(NOTIFICATION _ ID); ?
stop self();
? }
? },
100);
? }
? }
? }
Before taking the foreground service, start the application, and the value of oom_adj is 0. After pressing the return key, it becomes 9 (No.
May be different fROM rom)
Wake-up means that if AliPay, Taobao, Tmall, UC and other Ali apps are installed in your mobile phone,
Then after you open any Ali app, it is possible to wake up other Ali apps by the way.
This is entirely possible. In addition, the broadcast generated by the system is used when starting, switching networks, taking photos and shooting videos.
You can also wake up the app, but Android N canceled these three broadcasts.
If the application wants to save your life, if QQ and WeChat are willing to save you, how many mobile phones don't have QQ and WeChat? or
Those who push SDK like Youmeng and homing pigeons also have the function of waking up the app.
Pull-live method
JobSheduler is used as a means to restore the process after death.
The biggest disadvantage of native process mode is power consumption, native
The reason why the process consumes power is that there are two ways to realize whether the main process is alive or not, in the native process, through infinite loop.
Or a timer, judging whether the main process is alive or not, and pulling when the main process is not alive. Secondly, systems above 5.0
Not supported. But JobSheduler can replace the native process mode above Android5.0, that is,
Users can be forced to turn off and pull up, so pro-testing is feasible.
JobSheduler@TargetApi(Build。 Version code. Lollipop)?
Public class MyJobService extends JobService {
? @ Overlay
? public void onCreate() {
? super . oncreate();
? startJobSheduler();
? }
public void startJobSheduler() {?
Try {
? JobInfo。 Builder builder = new job information. Builder( 1,new component name(get package name()、myjobservice . class . getname()));
builder . set periodic(5); builder . setpersisted(true); JobScheduler job scheduler =(job scheduler)
This.getSystemService (context. JOB _ SCHEDULER _ SERVICE);
job scheduler . schedule(builder . build());
}
catch
(Exceptions)
{ ex . printstacktrace(); } }
? @ Overwrite?
public boolean onStartJob(job parameters job parameters){
? Return false?
} @ Override public boolean onStopJob(job parameters job parameters){?
Return false?
}
? }
This is the system's own, and the onStartCommand method must have an integer return value, and this integer returns.
The return value is used to tell the system what to do if it is killed after the service is started. Although this scheme may
So, in some cases, or some customized rom may fail, I think we can make a more conservative plan.
1. Start _ Sticky
If the system is destroyed after the onStartCommand returns, the service will be recreated and called in turn.
OnCreate and onStartCommand (Note: According to the test, the following versions of Android2.3.3 will only call.
OnCreate doesn't call onstart command at all (Android 4.0 can do it), which is equivalent to service.
Restart and return to the previous state).
2. Start _ not _ sticky
If the onStartCommand returns, the system will be destroyed. If this value is returned, it will be destroyed after execution.
If the service is terminated after the onStartCommand method, the system will not restart the service.
3. Start _ Redelivery _ Intention
A compatible version of START_STICKY, except that it does not guarantee that the service will be restarted after being terminated.
4. It is more powerful than sticky services and system services. This research comes from Iger, the system service mentioned here.
It's easy to understand, such as NotificationListenerService, which is a monitor.
Notification service, as long as the mobile phone receives the notification, NotificationListenerService can monitor the user immediately.
If you kill the process, you can restart it, so if you put this service into our process, then you can hehe.
View from a height or a distance
So if your application has a message push, you can cheat users in this way.