开发中异常的处理

- 实现未捕捉异常处理器
public class MyExceptionHandler implements UncaughtExceptionHandler {
private static final String TAG = "MyExceptionHandler";
@Override
public void uncaughtException(Thread arg0, Throwable arg1) {
Logger.i(TAG, "发生了异常,但是被哥捕获了...");
try {
Field[] fields = Build.class.getDeclaredFields();
StringBuffer sb = new StringBuffer();
for(Field field: fields){
String info = field.getName()+ ":"+field.get(null)+"\n";
sb.append(info);
}
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
arg1.printStackTrace(pw);
String errorlog = sw.toString();
File file = new File(Environment.getExternalStorageDirectory(),
"error.log");
FileOutputStream fos = new FileOutputStream(file);
sb.append(errorlog);
fos.write(sb.toString().getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
android.os.Process.killProcess(android.os.Process.myPid());
系统就会重启程序到出现错误之前的那个Activity。
}
}
- 让这个处理器生效
public class MobliesafeApplication extends Application {
public BlackNumberInfo info;
@Override
public void onCreate() {
super.onCreate();
Thread.currentThread().setUncaughtExceptionHandler(new MyExceptionHandler());
}
}