The Android implementation completely exits its own APP and kills all related processes

  • 2021-11-24 03:03:20
  • OfStack

Completely kill the code of App related processes


public void killAppProcess()
{
 // Note: You can't kill the main process first, otherwise the logic code can't continue to execute, you need to kill the related process first and finally kill the main process 
 ActivityManager mActivityManager = (ActivityManager)CurrentActivity.this.getSystemService(Context.ACTIVITY_SERVICE);
 List<ActivityManager.RunningAppProcessInfo> mList = mActivityManager.getRunningAppProcesses();
 for (ActivityManager.RunningAppProcessInfo runningAppProcessInfo : mList) 
 {
  if (runningAppProcessInfo.pid != android.os.Process.myPid()) 
  {
   android.os.Process.killProcess(runningAppProcessInfo.pid);
  }
 }
 android.os.Process.killProcess(android.os.Process.myPid());
 System.exit(0);
}

Pits needing attention

1. KillProcess()

android.os.Process.killProcess(android.os.Process.myPid())

You can kill the currently active process. This operation will clean up all resources (including threads) in the process. Of course, since ActivityManager is listening to the process at all times, 1 will try to restart the process once it finds that the process is abnormal from Kill.

This is why sometimes when we try to end the application in this way, we find that app will automatically restart.

2. System.exit()

System. exit () is the process-ending method in Java, which is called to shut down the current JVM virtual machine.

//indicates normal exit;
System.exit(0);
//indicates an abnormal exit, which should normally be placed in the catch block
System.exit(1);

3. Restart after App crash

Use Android two lines of code to really kill your App

The article in the above link is well written and comprehensive, so please refer to it


Related articles: