Android APP Survival Detection Mode

  • 2021-11-29 08:21:34
  • OfStack

Developers who have a little in-depth knowledge of Android know that the lifecycle state of all components in each APP in Android is maintained by the ActivityManagerService (AMS for short) process, so when an APP is kill or accidentally crash, the AMS process will maintain the components of APP in the first time.

Today, we will not look at the process of maintaining APP by AMS process, but only at what means AMS was notified in the first time, and whether we can apply this means to our APP. In a multi-process environment, mutual monitoring between processes by this means plays a guardian role.

We know that one APP corresponds to only 11 ActivityThread, which is also the real entrance of one APP. When ActivityThread # main is executed, it will attach to AMS process, and then AMS process will maintain the state of APP. Then the key point is on attach.

See the following code: ActivityManagerService # attachApplicationLocked ()


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

  ...

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

  ...

  return true;
 }

The line of code highlighted above is the key point. This is done using IBinder # linkToDeath. The first parameter of the linkToDeath method receives an interface implementation of android. os. IBinder. DeathRecipient to receive notifications of app death.

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

Interested students can enter the source code to view detailed comments, so there is no comment posted here. Source code DeathRecipient implementation is AppDeathRecipient to complete, this process is mainly AMS to clean up the current APP process corresponding component resources.

Through the above understanding, in our APP to use the above means, multiple processes to play the role of guarding each other, may need to get each other's IBinder object.

To get the IBinder object, refer to the following:

1. Receiving IBinder objects on onServiceConnected through Context # bindService;

2. By creating an android. os. Messenger object, and then passing this object to the opposite process through intent;

3. Direct new Binder rewrites onTransact, and then passes this Binder object to the other process through intent;


Related articles: