全局异常捕获类

/**

全局异常捕获类

*/
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);
}
}

猜你喜欢

转载自blog.csdn.net/weixin_42791904/article/details/83858179