How does Android get app crash logs

Once any error occurs in the Android APP, it will stop running. This is a headache for many developers.

In many cases, some hidden bugs passed in the testing department, and a small area crash occurred after they were put on the shelves. At this time, the error was reported because there was no log, which made it impossible to find the bug.

So, can it only be reproduced through user feedback and consume a lot of manpower and time?

In fact, as long as you insert a small piece of code in Application, you can capture all the complete error logs:

        //记录崩溃信息
        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();

                //最后如何处理这个崩溃,这里使用默认的处理方式让APP停止运行
                defaultHandler.uncaughtException(thread, throwable);
            }
        });

Engineers who have self-cultivation are not ready to get up~

Finally, it is the universal convention. If you think this blog is helpful to you, send a red envelope to the blogger~

 

Guess you like

Origin blog.csdn.net/u014653815/article/details/81363869