当进程异常终止时,可以在进程的Application中设置异常终止的监听并重启相关服务。
Thread.setDefaultUncaughtExceptionHandler(this);
@Override
public void uncaughtException(Thread thread, Throwable throwable) {
if(thread != null && "main".equals(thread.getName())) {
try {
Process.killProcess(Process.myPid());
System.runFinalizersOnExit(true);
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(intent);
} catch (Throwable throwable1) {
throwable1.printStackTrace();
}
} else {
try {
if(thread != null && !thread.isInterrupted()) {
thread.interrupt();
}
Process.killProcess(Process.myPid());
System.runFinalizersOnExit(true);
} catch (Exception e) {
e.printStackTrace();
}
}
Intent newIntent = new Intent(getApplicationContext(), MyService.class);
}