如何监控app的崩溃

1,261 阅读2分钟
原文链接: mp.weixin.qq.com

欢迎推荐人才赚取三位数以上的佣金,活动规则,只要邀请被推荐人关注公众号点击"面试内推",同时回复他的ID给小A,小A会在被推荐人成功入职后跟你分享佣金。佣金有多少呢?文末有惊喜!下面进入今天的正题。

当我们的app上线到应用市场之后,它发生了什么崩溃其实我们是不知道的。今天我们介绍一个方法来监控和收集用户手机上的异常崩溃同时上报给我们自己。

CrashHandler

在Thread的代码中,有一个接口

@FunctionalInterfacepublic interface UncaughtExceptionHandler {    /**     * Method invoked when the given thread terminates due to the     * given uncaught exception.     * <p>Any exception thrown by this method will be ignored by the     * Java Virtual Machine.     * @param t the thread     * @param e the exception     */    void uncaughtException(Thread t, Throwable e);}

`当线程崩溃的时候,会回调这个接口来通知当前发生了什么异常。这就是我们用来获取崩溃的方法。通常我们会定义一个CrashHandler,然后在Application初始化时注入这个Handler,这样在程序崩溃的时候就可以抓到异常了。

具体实现

public class CrashHandler implements UncaughtExceptionHandler {    private static CrashHandler instance;    public static CrashHandler getInstance() {        if (instance == null) {            instance = new CrashHandler();        }        return instance;    }    public void init(Context ctx) {        Thread.setDefaultUncaughtExceptionHandler(this);    }    /**     * 核心方法,当程序crash 会回调此方法, Throwable中存放这错误日志     */    @Override    public void uncaughtException(Thread arg0, Throwable arg1) {        //收集并反馈异常        android.os.Process.killProcess(android.os.Process.myPid());    }}

使用很简单,在Application中调用就行,

CrashHandler crashHandler = CrashHandler.getInstance();        crashHandler.init(getApplicationContext());

这样一来就可以在uncaughtException中做我们想做的事情,比如写入文件,或者上传到我们的服务器。

请随意转发下图到微信群或朋友圈,内推成功的同学,小A将与你分享4位数的佣金哦,最低也有1000大洋!

想了解更多开发知识?请点击阅读原文!