Android小技巧 Part III——How to get Android crash logs

来源:互联网 发布:电商商品排序算法 编辑:程序博客网 时间:2024/06/05 16:50

Android开发遇到程序crash时,常常无法看到log,给开发调试带来了不小的困难,通过下面的简单方法,可以有效的获取log并输出出来(通过Logcat、日志文件等等)。

自定义ExceptionHandler,继承Thread.UncaughtExceptionHandler

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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

1
2
3
4
5
6
7
8
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Thread.setDefaultUncaughtExceptionHandler(new TopExceptionHandler(this));
//TODO;
//……
}