Android全局异常的捕获
为了更好的完善我们的项目,通常需要对产品不停的迭代维护,计时的收集用户使用过程中发生的异常信息就显得非常重要。市面上有一些第三方工具提供该功能:例如:腾讯的Bugly、友盟统计等。
但是有时间为了减少我们的apk的大小或公司要求,会禁止使用这些第三方工具,所以我们需要自己提供这个简单的功能。
Thread.UncaughtExceptionHandler接口
当程序发生异常终止时,如果我们没有对其进行异常捕获处理,系统会调用该线程组的默认异常捕获处理器。我们想要对应用全局的异常进行捕获,实现思路就是自己写一个捕获器去替换系统默认的,然后对设备信息、版本信息、异常信息进行收集并上传到服务器进行分析。
Android 提供了这样一个接口Thread.UncaughtExceptionHandler
/**
* Implemented by objects that want to handle cases where a thread is being
* terminated by an uncaught exception. Upon such termination, the handler
* is notified of the terminating thread and causal exception. If there is
* no explicit handler set then the thread's group is the default handler.
*/
public static interface UncaughtExceptionHandler {
/**
* The thread is being terminated by an uncaught exception. Further
* exceptions thrown in this method are prevent the remainder of the
* method from executing, but are otherwise ignored.
*
* @param thread the thread that has an uncaught exception