Android保存App异常信息到本地
本文实例为大家分享了Android保存App异常信息到本地的具体代码,供大家参考,具体内容如下
首先添加权限
代码
//调用该方法造成异常
privatevoidmath(){
try{
inta=0;
intb=10;
intc=b/a;
}catch(Exceptione){
e.printStackTrace();//Logcat打印异常
//保存异常信息
StringWritersw=newStringWriter();
e.printStackTrace(newPrintWriter(sw,true));
saveException(this,sw.toString());
}
}
/**
*保存异常信息到本地Android/data/包名/files/Documents/exception/yyyyMMdd_app_exception.txt
*@paramcontext上下文
*@paramerrMsg异常信息
*/
privatevoidsaveException(Contextcontext,StringerrMsg){
if(context==null||TextUtils.isEmpty(errMsg))return;
FileOutputStreamfos=null;
try{
//创建目录
StringdirPath=context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getPath()+"/exception/";
Filedir=newFile(dirPath);
if(!dir.exists()){
dir.mkdirs();
}
//根据当天日期来生成文件名
Stringdate=newSimpleDateFormat("yyyyMMdd",Locale.ENGLISH).format(newDate());
//创建文件
Filefile=newFile(dirPath,date+"_app_exception.txt");
if(!file.exists()){
file.createNewFile();
}
fos=newFileOutputStream(file,true);
fos.write(errMsg.getBytes());
fos.write("\n".getBytes());
fos.flush();
}catch(Exceptione){
e.printStackTrace();
}finally{
if(fos!=null){
try{
fos.close();
}catch(Exceptione){
e.printStackTrace();
}
}
}
}
效果如图
可以考虑将当前时间写进文件,更方便排查问题
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。