SoFunction
Updated on 2025-04-09

Android APP survival detection method

Developers who have a little deeper understanding of Android know that the life cycle state of all components in each APP in Android is maintained by the ActivityManagerService (AMS) process, so when an APP is killed or accidentally crashed, the AMS process will maintain the APP components as soon as possible.

Today we will not look at the process of maintaining the AMS process, but only look at the means by which AMS gets the notification as soon as possible. Whether we can apply this means to our APP, and in a multi-process environment, the mutual monitoring between processes plays a guardian role through this means.

We know that an APP corresponds to the only ActivityThread, which is also the real entrance to an APP. When ActivityThread#main is executed, it will be attached to the AMS process, and the AMS process will maintain the state of the APP in the future. Then the key point is on the attachment.

See the following code: ActivityManagerService#attachApplicationLocked()

private final boolean attachApplicationLocked(IApplicationThread thread,
   int pid) {

  ...

  final String processName = ;
  try {
   AppDeathRecipient adr = new AppDeathRecipient(
     app, pid, thread);
   <span style="background-color: rgb(255, 255, 51);"><strong>().linkToDeath(adr, 0);</strong></span>
    = adr;
  } catch (RemoteException e) {
   (mProcessStats);
   startProcessLocked(app, "link fail", processName);
   return false;
  }

  ...

  return true;
 }

The line of code highlighted above is the key point. IBinder#linkToDeath is used to do it. The first parameter of the linkToDeath method receives an interface implementation, which is used to receive notifications of app death.

Of course, you can also cancel the listening through IBinder#unlinkToDeath.

Interested students can enter the source code to view detailed comments, so I will not post comments here. The implementation of DeathRecipient in the source code is completed by AppDeathRecipient. This processing is mainly AMS to clean up the component resources corresponding to the current APP process.

Through the above understanding, we need to use the above methods in our APP. To protect the other party between multiple processes, we may need to obtain the other party's IBinder object.

For the method to obtain the IBinder object, refer to the following:

1. Receive the IBinder object on onServiceConnected through Context#bindService;

2. Create an object and then pass this object to the other party's process through intent;

3. Directly rewrite onTransact by new Binder, and then pass this Binder object to the other party's process through intent;

The above Android APP survival detection method is all the content I share with you. I hope you can give you a reference and I hope you can support me more.