欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

全局异常捕获类

程序员文章站 2022-04-21 17:56:06
...

/**

全局异常捕获类

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

相关标签: 全局异常捕获类