您的位置:首页 > 编程语言

安卓捕获应用的运行时异常并保存代码

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();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: