当我们的app上线到应用市场之后,它发生了什么崩溃其实我们是不知道的。今天我们介绍一个方法来监控和收集用户手机上的异常崩溃同时上报给我们自己。
在Thread的代码中,有一个接口
@FunctionalInterface
public 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中做我们想做的事情,比如写入文件,或者上传到我们的服务器。