之前也写过几次关于UnCaughtException的博客,但是感觉实用性不好,特此记录以下:
public class App extends Application{
@Override
public void onCreate() {
super.onCreate();
Thread.setDefaultUncaughtExceptionHandler(new CrashHandler());
}
public class CrashHandler implements Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread thread, Throwable ex) {
StringWriter stringWriter=new StringWriter();
PrintWriter printWriter=new PrintWriter(stringWriter);
ex.printStackTrace(printWriter);
printWriter.close();
String unCaughtException=stringWriter.toString();//详细错误日志
Log.e("崩溃",thread.getName()+unCaughtException);
restartApp();//重启App
}
}
public void restartApp(){
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(intent);
android.os.Process.killProcess(android.os.Process.myPid()); //结束进程之前可以把你程序的注销或者退出代码放在这段代码之前
}
}