我希望应用程序在崩溃时自动重启。我目前已经使用 DefaultUncaughtExceptionHandler 实现了这一点,但有时当应用程序崩溃时,它会发送对话框“不幸的是应用程序已停止”并且它不会重新启动。如何避免对话框并在每次崩溃时重新启动应用程序?
谢谢。
@Override
public void uncaughtException(Thread thread, Throwable ex) {
try {
Intent intent = new Intent(activity, FrontActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
application.getBaseContext(), 0, intent,
PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_CANCEL_CURRENT);
//Following code will restart your application after 2 seconds
AlarmManager mgr = (AlarmManager) application.getBaseContext()
.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000,
pendingIntent);
//This will finish your activity manually
activity.finish();
//This will stop your application and take out from it.
System.exit(2);
} catch (RuntimeException e) {
e.printStackTrace();
}
}