Chinaunix首页 | 论坛 | 博客
  • 博客访问: 376189
  • 博文数量: 284
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1707
  • 用 户 组: 普通用户
  • 注册时间: 2014-05-14 16:38
文章分类

全部博文(284)

文章存档

2015年(6)

2014年(278)

我的朋友

分类: Android平台

2014-06-25 15:55:54

将导致程序崩溃的堆栈调用Log写入文件,便于收集bug。在调试安卓程序,由于某些原因调试时手机不能连接PC端,无法通过IDE查看程序崩溃的Log,希望log能够写入文件中,对于已经发布的App可以通过该功能收集Bug。
01import java.io.FileNotFoundException;
02import java.io.FileOutputStream;
03import java.io.IOException;
04import java.io.PrintStream;
05import java.lang.Thread.UncaughtExceptionHandler;
06 
07public 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}
阅读(531) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~