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

全局异常捕获

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

首先创建一个类,为Singloton类型,并且继承  Thread.UncaughtExceptionHandler

其中java代码如下:

public class Ex implements Thread.UncaughtExceptionHandler {
    private static final Ex ourInstance = new Ex();
    private Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler;


    public static Ex getInstance() {
        return ourInstance;
    }

    private Ex() {
    }
    private Context context;
    public void initException(Context context){
//        获取默认异常捕获
        defaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
//        设置
        Thread.setDefaultUncaughtExceptionHandler(this);
        this.context = context;
    }

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        Log.i("aaa",e+""+"................."+t+"");
        Intent intent = new Intent("com.bwie.zhanglu.view.ui.errer");

        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        context.startActivity(intent);

        //Process.killProcess(Process.myPid());
    }
}

然后只需要再全局配置一下就可以实现了,java代码入下:

public class MyAppliction extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        x.Ext.init(this);
        Ex.getInstance().initException(this);
    }
}