首先是在Application中实现接口
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
Thread.setDefaultUncaughtExceptionHandler(
new MYExceptionHandler());
}
/**
* 当app出现异常就会走下面的方法!!!
* */
class MYExceptionHandler implements Thread.UncaughtExceptionHandler{
@Override
public void uncaughtException(Thread thread, Throwable throwable) {
if (throwable !=
null) {
final Writer result =
new StringWriter();
final PrintWriter printWriter =
new PrintWriter(result);
throwable.printStackTrace(printWriter);
String errorReport = result.toString();
Log.d(
"-<<<<>" , errorReport);
saveInFile(errorReport );
}
}
}
private void saveInFile(String errorReport) {
FileOutputStream out =
null ;
File file =
new File(Environment.getExternalStorageDirectory() ,
"error-log.txt");
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
try {
out =
new FileOutputStream(file);
out.write(errorReport.getBytes());
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (out !=
null)
try {
out.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
我这个项目是如果异常了,就再次启动自己
public void uncaughtException(Thread thread, Throwable ex) {
if (ex !=
null) {
final Writer result =
new StringWriter();
final PrintWriter printWriter =
new PrintWriter(result);
ex.printStackTrace(printWriter);
String errorReport = result.toString();
Log.d(
"-<<<<>" , errorReport);
Intent intent =
new Intent(
"com.dopool.devinstall.TwoActivity");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(CATCH_EXCEPTION, errorReport);
mContent.startActivity(intent);
android.os.Process.killProcess(android.os.Process.myPid());
转载请注明原文地址: https://ju.6miu.com/read-900249.html