Android开发遇到程序crash时,常常无法看到log,给开发调试带来了不小的困难,通过下面的简单方法,可以有效的获取log并输出出来(通过Logcat、日志文件等等)。
自定义ExceptionHandler,继承Thread.UncaughtExceptionHandler
public class TopExceptionHandler implements Thread.UncaughtExceptionHandler {
private Thread.UncaughtExceptionHandler defaultUEH;
private Activity app = null;
public TopExceptionHandler(Activity app) {
this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
this.app = app;
}
public void uncaughtException(Thread t, Throwable e) {
StackTraceElement[] arr = e.getStackTrace();
String report = e.toString() + "\n\n";
report += "--------- Stack trace ---------\n\n";
for (int i = 0; i < arr.length; i++) {
report += " " + arr[i].toString() + "\n";
}
report += "-------------------------------\n\n";
//输出到LogCat
Log.e("XXX",report);
//输出到其他
//TODO;
defaultUEH.uncaughtException(t, e);
}
}
在Activity中使用Handler
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Thread.setDefaultUncaughtExceptionHandler(new TopExceptionHandler(this));
//TODO;
//……
}
网友评论