本文章转发自: https://blog.csdn.net/xy4_android/article/details/80846610
开发物联网项目时候,遇到这样一个问题,用户设备安装应用后程序直接崩溃,但是由于无法使用,用户设备进行调试,又因为某些原因没有集成第三方的bug统计,所以想到,将应用的崩溃日志,存储到本地,然后进行分析.
代码是我直接复制来的,大家可以直接去原创博客查看(https://blog.csdn.net/xy4_android/article/details/80846610),
我在项目里直接使用没有问题.
public class MyCrashHandler implements Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
Log.e("程序出现异常了", "Thread = " + t.getName() + "\nThrowable = " + e.getMessage());
String stackTraceInfo = getStackTraceInfo(e);
Log.e("stackTraceInfo", stackTraceInfo);
saveThrowableMessage(stackTraceInfo);
}
/**
* 获取错误的信息
*
* @param throwable
* @return
*/
private String getStackTraceInfo(final Throwable throwable) {
PrintWriter pw = null;
Writer writer = new StringWriter();
try {
pw = new PrintWriter(writer);
throwable.printStackTrace(pw);
} catch (Exception e) {
return "";
} finally {
if (pw != null) {
pw.close();
}
}
return writer.toString();
}
private String logFilePath = Environment.getExternalStorageDirectory() + File.separator + "Android" +
File.separator + "data" + File.separator + MyApp.getInstance().getPackageName() + File.separator + "crashLog";
private void saveThrowableMessage(String errorMessage) {
if (TextUtils.isEmpty(errorMessage)) {
return;
}
File file = new File(logFilePath);
if (!file.exists()) {
boolean mkdirs = file.mkdirs();
if (mkdirs) {
writeStringToFile(errorMessage, file);
}
} else {
writeStringToFile(errorMessage, file);
}
}
private void writeStringToFile(final String errorMessage, final File file) {
new Thread(new Runnable() {
@Override
public void run() {
FileOutputStream outputStream = null;
try {
ByteArrayInputStream inputStream = new ByteArrayInputStream(errorMessage.getBytes());
outputStream = new FileOutputStream(new File(file, System.currentTimeMillis() + ".txt"));
int len = 0;
byte[] bytes = new byte[1024];
while ((len = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, len);
}
outputStream.flush();
Log.e("程序出异常了", "写入本地文件成功:" + file.getAbsolutePath());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}).start();
}
}
public class MyApp extends Application {
@Override
public void onCreate() {
super.onCreate();
MyCrashHandler handler = new MyCrashHandler();
Thread.setDefaultUncaughtExceptionHandler(handler);
}
}