在Application中加入一下代码
Java:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27//获取崩溃信息 final Thread.UncaughtExceptionHandler defaultHandler = Thread.getDefaultUncaughtExceptionHandler(); Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread thread, Throwable throwable) { //获取崩溃时的UNIX时间戳 long timeMillis = System.currentTimeMillis(); //时间戳转换 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(); //写入文件 writeLog(errorLog) //如何处理该崩溃,下面使用默认的处理方式让APP停止运行 defaultHandler.uncaughtException(thread, throwable); } });
Kotlin:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22val defaultHandler = Thread.getDefaultUncaughtExceptionHandler() Thread.setDefaultUncaughtExceptionHandler { thread, throwable -> //获取崩溃时的UNIX时间戳 val timeMillis = System.currentTimeMillis() //时间戳转换 val stringBuilder = StringBuilder(SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Date(timeMillis))) stringBuilder.append(":n") //获取错误信息 stringBuilder.append(throwable.message) stringBuilder.append("n") //获取堆栈信息 val sw = StringWriter() val pw = PrintWriter(sw) throwable.printStackTrace(pw) stringBuilder.append(sw.toString()) //拿到的错误信息 val errorLog: String = stringBuilder.toString() //写入文件 writeLog(errorLog) //如何处理该崩溃,下面使用默认的处理方式让APP停止运行 // defaultHandler.uncaughtException(thread, throwable) }
writeLog方法:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17/* *作者:赵星海 CSDN-深海呐 *时间:2021/3/13 11:44 *用途:日志写入文件, 文件名:LOG.txt */ fun writeLog(text: String?) { var textR = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(Date().time) + " " + text + "rn" try { var fos = FileOutputStream("LOG.txt", true) fos.write(textR.toByteArray()) fos.close() } catch (e: FileNotFoundException) { e.printStackTrace() } catch (e: IOException) { e.printStackTrace() } }
最后
以上就是务实世界最近收集整理的关于Android 获取APP崩溃日志并写入本地的全部内容,更多相关Android内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复