安卓捕获应用的运行时异常并保存代码
2016-01-04 22:02
591 查看
// 捕获应用的运行时异常
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {// 给主线程设置一个处理运行时异常的handler
@Override
public void uncaughtException(Thread thread, final Throwable ex) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
StringBuilder sb = new StringBuilder();
sb.append("Version code is ");
sb.append(Build.VERSION.SDK_INT + "\n");// 设备的Android版本号
sb.append("Model is ");
sb.append(Build.MODEL + "\n");// 设备型号
sb.append(sw.toString());
try {
saveToSDCard("myException.txt", sb.toString());
} catch (IOException e) {
e.printStackTrace();
}
System.exit(0);
}
});
public void saveToSDCard(String fileName, String content)
throws IOException {
// 考虑不同版本的sdCard目录不同,采用系统提供的API获取SD卡的目录
File file = new File(Environment.getExternalStorageDirectory(),
fileName);
if (!file.isDirectory()) {
file.createNewFile();
}
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(content.getBytes());
fileOutputStream.close();
}
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {// 给主线程设置一个处理运行时异常的handler
@Override
public void uncaughtException(Thread thread, final Throwable ex) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
StringBuilder sb = new StringBuilder();
sb.append("Version code is ");
sb.append(Build.VERSION.SDK_INT + "\n");// 设备的Android版本号
sb.append("Model is ");
sb.append(Build.MODEL + "\n");// 设备型号
sb.append(sw.toString());
try {
saveToSDCard("myException.txt", sb.toString());
} catch (IOException e) {
e.printStackTrace();
}
System.exit(0);
}
});
public void saveToSDCard(String fileName, String content)
throws IOException {
// 考虑不同版本的sdCard目录不同,采用系统提供的API获取SD卡的目录
File file = new File(Environment.getExternalStorageDirectory(),
fileName);
if (!file.isDirectory()) {
file.createNewFile();
}
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(content.getBytes());
fileOutputStream.close();
}
相关文章推荐
- 64.scala编程思想笔记——使用元组的模式匹配
- 63.scala编程思想笔记——引用和可修改性
- 62.scala编程思想笔记——映射表
- 61.scala编程思想笔记——集
- 60.scala编程思想笔记——将序列与zip相结合
- 59.scala编程思想笔记——列表和递归
- php随手记
- 58.scala编程思想笔记——序列
- matlab2013b调用cpp文件,mex,VS2013配置问题
- C语言中,头文件和源文件的关系(转)
- django-simple-captcha 使用 以及添加动态ajax刷新验证
- java读取/写入属性文件
- Java 泛型具体解释
- 用代码判断大小端
- 第4讲C语言程序初体验-练习
- python 编程小实例(2) 四则运算小游戏
- c#与c++交互
- Arrays.asList() 返回的list不能add,remove以及慎用java.util.Collections.copy()方法
- 设计模式学习笔记--装饰者模式(Decorator Pattern)
- Java中父类和子类关于构造方法和私有属性的几个问题