Thread.setDefaultUncaughtExceptionHandler(new UEHandler(this));
---设置当线程由于未捕获到异常而突然终止,并且没有为该线程定义其他处理程序时所调用的默认处理程序
UEHandler实现了Thread.UncaughtExceptionHandler接口
当某一线程因未捕获的异常而即将终止时,Java 虚拟机将使用 Thread.getUncaughtExceptionHandler() 查询该线程以获得其 UncaughtExceptionHandler 的线程,并调用处理程序的 uncaughtException 方法,将线程和异常作为参数传递。如果某一线程没有明确设置其 UncaughtExceptionHandler,则将它的 ThreadGroup 对象作为其 UncaughtExceptionHandler。如果 ThreadGroup 对象对处理异常没有什么特殊要求,那么它可以将调用转发给默认的未捕获异常处理程序
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import android.util.Log;
public class UEHandler implements Thread.UncaughtExceptionHandler {
private Myapp softApp;
public UEHandler(Myapp app) {
softApp = app;
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
String info = null;
ByteArrayOutputStream baos = null;
PrintStream printStream = null;
try {
baos = new ByteArrayOutputStream();
printStream = new PrintStream(baos);
ex.printStackTrace(printStream);
byte[] data = baos.toByteArray();
info = new String(data);
data = null;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (printStream != null) {
printStream.close();
}
if (baos != null) {
baos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
// print
long threadId = thread.getId();
Log.w("ANDROID_ZD", "Thread.getName()=" + thread.getName() + " id=" + threadId + " state=" + thread.getState());
Log.w("ANDROID_ZD", "Error[" + info + "]");
if (threadId != 1) {
// 此处示例跳转到汇报异常界面。
} else {
// 此处示例发生异常后,重新启动应用
// // kill App Progress
// android.os.Process.killProcess(android.os.Process.myPid());
}
}
private void write2ErrorLog(File file, String content) {
FileOutputStream fos = null;
try {
if (file.exists()) {
// 清空之前的记录
file.delete();
} else {
file.getParentFile().mkdirs();
}
file.createNewFile();
fos = new FileOutputStream(file);
fos.write(content.getBytes());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}