无论你的代码写得多么优秀,测试如何充分都避免不了异常的产生,应用都是存在bug的只有我们一步一步去修复,一版一版的更新才会更加的好!谁才是应用的真正测试者和体验者呢?----那就是用户,作为一个优秀的开发者是不怕面对bug的提出和发现,开发者应该享受修复bug的成就感,但是一款应用上线了出现异常我们无法知道的,那我们要通过什么来进行反馈呢?------crash异常收集
首先要说的是UncaughtExceptionHandler这个类,看名字就知道这是一个我只异常处理类. 它是Thread类中的一个接口:
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
* @param ex the exception that was thrown
*/
void uncaughtException(Thread thread, Throwable ex);
}
那么我们需要实现该接口,uncaughtEXception(Thread thread,Throwable ex);
第一步实现该接口:
package com.example.test;
import android.content.Context;
import java.lang.Thread.UncaughtExceptionHandler;
public class MyException implements UncaughtExceptionHandler {
private Thread.UncaughtExceptionHandler defaultUnHandler;
private static MyException INSTANCE = null;
public static synchronized MyException getInstance() {
if (INSTANCE == null) {
INSTANCE = new MyException();
}
return INSTANCE;
}
public void init(Context context) {
// 获取系统默认的异常处理类
defaultUnHandler = Thread.getDefaultUncaughtExceptionHandler();
// 当前的类设置系统默认异常处理类
Thread.setDefaultUncaughtExceptionHandler(this);
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
sendTheEXceptionToServer(ex);
}
public void sendTheEXceptionToServer(Throwable ex) {
// 把所需要的异常信息发送到服务器,以便于问题的修复
}
}
第二不在编写自己的Application类
public class MyApplication extends Application {
private final static String TAG = MyApplication.class.getSimpleName();
@Override
public void onCreate() {
super.onCreate();
MyException.getInstance().init();
}
}
配置AndroidManifest.xml文件;
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
>