Android记录程序崩溃Log写入文件
扫描二维码
随时随地手机看文章
将导致程序崩溃的堆栈调用Log写入文件,便于收集bug。在调试安卓程序,由于某些原因调试时手机不能连接PC端,无法通过IDE查看程序崩溃的Log,希望log能够写入文件中,对于已经发布的App可以通过该功能收集Bug。
01 |
import java.io.FileNotFoundException; |
02 |
import java.io.FileOutputStream; |
03 |
import java.io.IOException; |
04 |
import java.io.PrintStream; |
05 |
import java.lang.Thread.UncaughtExceptionHandler; |
06 |
07 |
public class MyCrashHandler implements UncaughtExceptionHandler{ |
08 |
09 |
private static MyCrashHandler crashHandler; |
10 |
|
11 |
@Override |
12 |
public void uncaughtException(Thread thread, Throwable ex) { |
13 |
// TODO Auto-generated method stub |
14 |
if (crashHandler != null ) { |
15 |
try { |
16 |
//将crash log写入文件 |
17 |
FileOutputStream fileOutputStream = new FileOutputStream( "/mnt/sdcard/crash_log.txt" , true ); |
18 |
PrintStream printStream = new PrintStream(fileOutputStream); |
19 |
ex.printStackTrace(printStream); |
20 |
printStream.flush(); |
21 |
printStream.close(); |
22 |
fileOutputStream.close(); |
23 |
} catch (FileNotFoundException e) { |
24 |
// TODO Auto-generated catch block |
25 |
e.printStackTrace(); |
26 |
} catch (IOException e) { |
27 |
// TODO Auto-generated catch block |
28 |
e.printStackTrace(); |
29 |
} |
30 |
} |
31 |
} |
32 |
|
33 |
//设置默认处理器 |
34 |
public void init() { |
35 |
Thread.setDefaultUncaughtExceptionHandler( this ); |
36 |
} |
37 |
|
38 |
private MyCrashHandler() {} |
39 |
|
40 |
//单例 |
41 |
public static MyCrashHandler instance() { |
42 |
if (crashHandler == null ) { |
43 |
synchronized (crashHandler) { |
44 |
crashHandler = new MyCrashHandler(); |
45 |
} |
46 |
} |
47 |
return crashHandler; |
48 |
} |
49 |
} |