Summary of Methods for Automatic Restart of Android after Application of Crash

  • 2021-12-04 11:22:22
  • OfStack

Premise

First of all, we must definitely register an CrashHandler in Application and listen to the application crash


public class TestApplication extends MultiDexApplication {
 private static TestApplication mInstance;
 @Override
 public void onCreate() {
  super.onCreate();
  Thread.setDefaultUncaughtExceptionHandler(new CrashHandler());
   }

Then find a way to restart the application in this CrashHandler. There are two methods as follows:

Method 1. Pass AlarmManager


 public class CrashHandler implements Thread.UncaughtExceptionHandler {
 @Override
 public void uncaughtException(Thread t, Throwable e) {

  // Restart app
  /**
   *  This way   The function can be achieved 
   *  But the problem is that if you say yours app Hang up   The system desktop is displayed 
   *  And then your app It's starting up 
   *  It doesn't feel very good 
   */
  Intent intent = new Intent();
  Context context = TestApplication.getInstance();
  intent.setClass(context, MainActivity.class);
  intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  context.startActivity(intent);
  PendingIntent pendingIntent = PendingIntent.getActivity(context,0,intent,PendingIntent.FLAG_ONE_SHOT);
  AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
  alarmManager.set(AlarmManager.RTC,System.currentTimeMillis() + 100,pendingIntent);
  Process.killProcess(Process.myPid());
  System.exit(0);

 }
}

Method 2:

Use the third party library


 implementation 'com.jakewharton:process-phoenix:2.0.0'

public class CrashHandler implements Thread.UncaughtExceptionHandler {
 @Override
 public void uncaughtException(Thread t, Throwable e) {

  ProcessPhoenix.triggerRebirth(TestApplication.getInstance());
 }
}

The principle of this third square library is:
When app crashed, ProcessPhoenix.triggerRebirth(TestApplication.getInstance()); It triggers an Activity that starts another process, and then ends the currently crashed process. In the Activity of the new process, start up the application in your own process.

Summarize


Related articles: