获取App的崩溃信息
将以下代码放到Application的onCreate()中
private void logMessage{
//记录崩溃信息
final Thread.UncaughtExceptionHandler defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable throwable) {
//获取崩溃时的UNIX时间戳
long timeMillis = System.currentTimeMillis();
//将时间戳转换成人类能看懂的格式,建立一个String拼接器
StringBuilder stringBuilder =new StringBuilder(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date(timeMillis)));
stringBuilder.append(":\n");
//获取错误信息
stringBuilder.append(throwable.getMessage());
stringBuilder.append("\n");
//获取堆栈信息
StringWriter sw =new StringWriter();
PrintWriter pw =new PrintWriter(sw);
throwable.printStackTrace(pw);
stringBuilder.append(sw.toString());
//这就是完整的错误信息,保存到本地
String errorLog = stringBuilder.toString();
//将错误信息写入到文件中
FileUtils.setAppendFile(errorLog);
//最后处理这个崩溃,这里使用默认的处理方式让APP停止运行
defaultHandler.uncaughtException(thread, throwable);
}
});
}
写入到文件的工具类
import android.os.Environment;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
public class FileUtils {
private static final String appName = "yourAppName";
private static File file;
static {
file = new File(Environment.getExternalStorageDirectory(), appName);
if (!file.exists()) {
file.mkdirs();
}
file = new File(file, "log.txt");
}
/**
* 将文本追加写入到文件
*/
public static void setAppendFile(String value) {
FileWriter fw;
BufferedWriter bw;
PrintWriter printWriter = null;
try {
fw = new FileWriter(file, true);
bw = new BufferedWriter(fw);
printWriter = new PrintWriter(bw);
printWriter.println(value);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (printWriter != null) {
printWriter.close();
}
}
}
}
参考链接,感谢这位大佬的分享https://www.jianshu.com/p/644078912cfd