前言
作为一个android开发,经常遇到crash情况。原因各种各样,即使是经过了测试的大量检测,但是到用户手上还是会遇到闪退。这和android设备的碎片化有关,也和使用时的环境有关,比如弱网,比如高铁频繁切换小区等等。然而我们不能让用户帮我们抓取log,那要怎么才能知道为什么闪退了呢?
UncaughtExceptionHandler
幸运的是:安卓已经帮我们想好了解决问题的接口(UncaughtExceptionHandler
)。从名称上就知道这是用来处理没有捕捉到的野生Exception的。平时我们try catch的Exception的那就叫捕捉到的。看一下UncaughtExceptionHandler
的源码:
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);
}
代码很简单,这是一个接口,并且只有一个方法。当出现未捕捉的exception时,系统会回调这个方法。具体实现在ThreadGroup.java
的uncaughtException
:
public void uncaughtException(Thread t, Throwable e) {
if (parent != null) {
parent.uncaughtException(t, e);
} else {
Thread.UncaughtExceptionHandler ueh =
Thread.getDefaultUncaughtExceptionHandler(); //获取当前默认的UncaughtExceptionHandler
if (ueh != null) {
ueh.uncaughtException(t, e); //此处回调uncaughtException()方法
} else if (!(e instanceof ThreadDeath)) {
System.err.print("Exception in thread \""
+ t.getName() + "\" ");
e.printStackTrace(System.err);
}
}
}
实现自己的UncaughtExceptionHandler
从上面的源码分析我们知道,只要我们重写一个类实现UncaughtExceptionHandler接口,替换当前线程的默认UncaughtExceptionHandler对象就行。系统为我们提供了方法Thread.getDefaultUncaughtExceptionHandler()
和Thread.setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler u)
。
public class CrashHandler implements Thread.UncaughtExceptionHandler {
private static final String TAG = CrashHandler.class.getSimpleName();
private static CrashHandler INSTANCE = new CrashHandler();
private Context mContext;
private Thread.UncaughtExceptionHandler mDefaultExceptionHandler;
@Override
public void uncaughtException(Thread t, Throwable e) {
//当发生exception时候会回调该方法
dumpToSDCard(t, e);