android中全局异常捕捉

只要写代码就会有bug,但是我们要想办法收集到客户的bug。有第三方bugly或者友盟等可以收集。但是,android原生就提供了有关收集异常的api,所以我们来学习一下。

异常捕捉实现

android中提供了Thread.UncaughtExceptionHandler类

1.创建Thread.UncaughtExceptionHandler对象

创建对象,实现uncaughtException方法,此方法可以接收到所有异常,要做的就是对异常进行处理。

一般是对错误日志进行本地化,并且杀掉进程

Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable ex) {
try {
//处理错误日志,此段代码是将错误日志,写入本地
writeErrorLog(ex);
Log.e(TAG, ex.getMessage(), ex);
ToastUtils.longMsg(ex.getMessage());
} finally {
//杀掉应用程序
// Try everything to make sure this process goes away.
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(10);
}
}
};

2.将自定义的handler对象设置给系统

Thread.setDefaultUncaughtExceptionHandler(handler);

3.一般情况,对异常的全局处理,会在application中进行

每个应用都会创建自己的application,具体创建就不细说了

将错误日志写到本地

/**
* 打印错误日志到日志文件中
*
* @param ex Exception
*/
public void writeErrorLog(final Throwable ex) {
File dir = StorageHelper.getInstance().getLogPath();
File file = new File(dir, String.format("%s.txt", getCurrentDateString()));
Log.d(TAG, "======" + dir.getAbsolutePath()); PrintStream printStream = null;
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file, true);
printStream = new PrintStream(fileOutputStream); /**
* 添加:出错的时间,设备号,安卓版本,App版本
*/
printStream.append("系统时间:").append(DateUtils.getCurrentTime(DateUtils.FORMAT_DATETIME));
printStream.append("\n设备类型:").append(DeviceUtils.getDeviceName());
printStream.append("\n设备号:").append(DeviceUtils.getUUID(EChatApp.getInstance()));
printStream.append("\nAndroid版本:").append(DeviceUtils.getReleaseVersion());
printStream.append("\nApp版本:").append(getVersion()).append("\n"); ex.printStackTrace(printStream);
fileOutputStream.close();
fileOutputStream = null;
} catch (Exception e) {
EMLog.e(TAG, e.getMessage(), e);
} finally {
IOUtils.closeQuietly(printStream);
IOUtils.closeQuietly(fileOutputStream);
}
}

ok。就介样了。

最新文章

  1. Intellij Idea/Webstorm/Phpstorm 的高效快捷键
  2. tomcat与oracle关于8080端口的冲突
  3. fopen()、 file_get_contents() 通过url获取链接内容
  4. 【BZOJ-1552&3506】robotic sort&排序机械臂 Splay
  5. NavBarControl
  6. JQuery_过滤选择器
  7. 1-9 TCP/IP参考模型
  8. Junit单元测试学习笔记二
  9. Oleans集群之Consul再解释
  10. 解决Oracle登录时出现无法处理服务名问题
  11. 使用ffmpeg转码时遇到aac报错
  12. NumPy的基本用法
  13. @Data的注解使用以及在IDEA上安装
  14. linux--- python3环境部署篇
  15. Zookeeper 在Windows下的安装过程及测试
  16. html学习笔记——ife task0001
  17. react 嵌套组件的通信
  18. Cassandra Demo--Python操作cassandra
  19. c# webBrowser全掌握
  20. 求值器本质--eval&apply

热门文章

  1. windows container (docker) 容器资料笔记
  2. Window下JDK安装与配置
  3. 关于Response.redirect和Response.End出现线程中止异常的处理
  4. Selenium 基本元素操作(参考)
  5. 1901: Zju2112 Dynamic Rankings
  6. 3018: [Usaco2012 Nov]Distant Pastures
  7. 2015: [Usaco2010 Feb]Chocolate Giving
  8. Lucene实战之初体验
  9. PowerDesigner建模应用(一)逆向工程,配置数据源并导出PDM文件
  10. JavaWeb之Listener监听器