1. 程式人生 > >全域性異常捕獲類

全域性異常捕獲類

/**

全域性異常捕獲類

*/
public class UnCatchExceptionHandler implements Thread.UncaughtExceptionHandler {

private Context context;
private Thread.UncaughtExceptionHandler mHandler;

private UnCatchExceptionHandler() {
}

private static UnCatchExceptionHandler mExceptionHandler = new UnCatchExceptionHandler();

public static UnCatchExceptionHandler getmExceptionHandler() {
    return mExceptionHandler;
}

public void init(Context context) {
    this.context = context.getApplicationContext();
    mHandler = Thread.getDefaultUncaughtExceptionHandler();
    Thread.setDefaultUncaughtExceptionHandler(this);
}

@Override
public void uncaughtException(Thread t, Throwable e) {
    if (mHandler != null) {
        mHandler.uncaughtException(t, e);
    } else { //否則我們自己處理,自己處理通常是讓app退出 Process.killProcess(Process.myPid()); }

    }
}

}

public class GenAndApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
//使用自定義全域性異常捕獲類
UnCatchExceptionHandler.getmExceptionHandler().init(this);
}
}