1.创建 MyApplication extends Application,然后在AndroidManifest.xml文件中的application标签下配置name属性,指向这个application;
2. 在MyApplication中重写OnCreate()方法添加代码,如下图:
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
//记录崩溃信息
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();
Log.e("测试", errorLog);
//把获取到的日志写到本地,ErrorText.txt文件名字可以自己定义
File rootFile = getRootFile(MyApplication.this);
Log.e("测试", rootFile.toString());
File file = new File(rootFile, "ErrorText.txt");
BufferedWriter bufferedWriter = null;
try {
//写入数据
bufferedWriter = new BufferedWriter(new FileWriter(file, true));
bufferedWriter.write(errorLog + "\r\n");
bufferedWriter.flush();
} catch (FileNotFoundException e) {
} catch (IOException e) {
} finally {
try {
if (null != bufferedWriter) {
bufferedWriter.close();
}
} catch (IOException e) {
}
}
//最后如何处理这个崩溃,这里使用默认的处理方式让APP停止运行
defaultHandler.uncaughtException(thread, throwable);
}
});
}
/**
* 安卓存储目录
*/
public static File getRootFile(Application application) {
//判断根目录
File rootFile = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
//Android Q 系统私有空间创建
///storage/emulated/0/Android/data/<package name>/files/ -- 应用卸载会删除该目录下所有文件
rootFile = application.getExternalFilesDir("");
} else {
//应用专属目录,位置/data/data//files
rootFile = application.getFilesDir();
}
return rootFile;
}
}
|