Android开发:捕获未捕捉的异常

未捕捉的异常会让应用Crash,如果是在用户处发生异常,我们无法得到日志,不好解决问题,友盟集成了错误日志收集功能,但我们也可以自己捕捉异常:
定义UnCaughtExceptionHandler,用于处理异常:

public class UnCaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        logToSdcard(thread,ex);
    }

    public static void logToSdcard(Thread thread,Throwable ex) {
        String logFilePath = "";
        FileWriter fw = null;
        PrintWriter pw = null;
        try {
            logFilePath = Environment.getExternalStorageDirectory().getPath()+"/crash.log";
            File logFile = new File(logFilePath);
            if (!logFile.exists()) {
                logFile.createNewFile();
            }
            fw = new FileWriter(logFile,true);
            pw = new PrintWriter(fw);
            pw.println(String.format("%s\t%s\t%s\t", new Date().toLocaleString(), thread.getName(), ex.toString()));
            Throwable cause= ex.getCause();
            StackTraceElement[] stackTraceElements=cause.getStackTrace();
            for (StackTraceElement stackTraceElement:stackTraceElements)
            {
                pw.println(String.format("%s\t%s\t%s\t", stackTraceElement.getClassName(), stackTraceElement.getLineNumber(), stackTraceElement.getMethodName()));
            }
            pw.close();
            fw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(pw != null){ try { pw.close(); } catch (Exception e) { }}
            if(fw != null){ try { fw.close(); } catch (Exception e) { }}
        }
    }
}

然后在Application中设置默认异常处理器:

Thread.setDefaultUncaughtExceptionHandler(
                new UnCaughtExceptionHandler());

© 2014, 冰冻鱼. 请尊重作者劳动成果,复制转载保留本站链接! 应用开发笔记

发表评论

电子邮件地址不会被公开。 必填项已用*标注