对于android程序,当我们不方便链接设备进行查看log输出,或者其他原因无法直接查看的情况,我们就可以采用把错误log记录在本地,然后发送到我们的服务器的方式来获取log信息。
那么,我们就会使用到这个方法
public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh) { defaultUncaughtExceptionHandler = eh; }这是Thread类的一个静态方法,作用就是
Set the default handler invoked when a thread abruptly terminates * due to an uncaught exception, and no other handler has been defined * for that thread.也就是相当于,在全局做了一个catch处理,对于那些没有被捕获的异常进行捕获,我们需要做的就是定义一个
UncaughtExceptionHandler然后通过setDefaultUncaughtExceptionHandler设置进去就可以。
private class MyUncaughtExceptionHandler implements UncaughtExceptionHandler { //Throwable 代表发生异常 @Override public void uncaughtException(Thread thread, Throwable ex) { ex.printStackTrace(); // 通过流写到一个文件 //ex.printStackTrace(err) FileUtils.string2File(getErrorInfo(ex), FileUtils.LOGPATH); android.os.Process.killProcess(android.os.Process.myPid());然后就能找到我们的log日志在路径 LOGPATH//杀死当前自己进程} /** * 获取错误的信息 * * @param arg1 * @return */ private String getErrorInfo(Throwable arg1) { Writer writer = new StringWriter(); PrintWriter pw = new PrintWriter(writer); arg1.printStackTrace(pw); pw.close(); String error = writer.toString(); return error; }}