my git :?https://github.com/hejiawang
?
? ? ? ?在软件开发中,无论我们怎么小心的写代码,进行测试,软件都会出现bug。
? ? ?
? ? ? ?开发Android程序时,可能因为用户使用的手机型号不同等原因,我们做好的程序还是有可能出现bug,也就是异常。那么我们就要将用户发生的这些异常记录下来,比如说,将用户发现的异常情况记录在用户手机的sd卡中,这样,客户在使用过程中突然系统崩溃了,找到了我们这些程序猿,我们就可以告诉客户把sd上的什么什么文件打给我,这样我们就能根据客户提供的异常信息找到bug了。
?
? ? ? 处理全局异常的步骤代码:
一、创建一个继承Application的类,别忘在配置文件中进行配置
public class TestApplication extends Application { @Override public void onCreate() { super.onCreate(); // 处理程序全局异常 Thread.currentThread().setUncaughtExceptionHandler( new MyUncaughtExceptionHandler()); } }
?二、创建一个实现UncaughtExceptionHandler接口的类,在下面的代码中,我记录的异常发生的时间,用户使用手机的型号等手机信息以及最重要的异常信息,并将这些信息存储在用户的sd卡上。代码如下:
/** * 处理程序全局异常 * * @author wang * */ public class MyUncaughtExceptionHandler implements UncaughtExceptionHandler { @SuppressWarnings("deprecation") @Override public void uncaughtException(Thread thread, Throwable ex) { try { StringBuffer sb = new StringBuffer(); //异常发生时间 long time = System.currentTimeMillis(); Date date = new Date(time); String timeStr = date.toGMTString(); sb.append(timeStr); sb.append("\n"); //用户使用的手机型号等信息 Field[] fields = Build.class.getDeclaredFields(); for (Field field : fields) { String name = field.getName(); String values = field.get(null).toString(); sb.append(name + " : " + values); sb.append("\n"); } //发生异常的具体情况 StringWriter sw = new StringWriter(); PrintWriter write = new PrintWriter(sw); ex.printStackTrace(write); String errorlog = sw.toString(); File log = new File("/sdcard/log.txt"); FileOutputStream fos; fos = new FileOutputStream(log); fos.write(sb.toString().getBytes()); fos.write(errorlog.getBytes()); fos.flush(); fos.close(); } catch (Exception e) { e.printStackTrace(); } // 绕过生命周期的顺序,强制关闭. android.os.Process.killProcess(android.os.Process.myPid()); } }
?
? ? ? ?这样,当用户使用软件时,发生莫名其妙的Exception时,就能记录下来了,如果用户找到程序猿,我们就能得到错误信息了
?
原文:http://hejiawangjava.iteye.com/blog/2249266