安卓全局異常捕捉

直接上代碼就是幹

public class ExceptionCapture implements Thread.UncaughtExceptionHandler {

    private static  ExceptionCapture exceptionCapture;
    private Context context;
    private Thread.UncaughtExceptionHandler defaultExceptionHander;

    public ExceptionCapture() {
    }


    public static ExceptionCapture getInstance(){
        if(exceptionCapture == null){
            synchronized (ExceptionCapture.class){
                if(exceptionCapture == null){
                    exceptionCapture=new ExceptionCapture();
                }
            }
        }
        return exceptionCapture;
    }

    /**
     * 替換默認的異常捕獲類
     * @param context
     */
    public void init(Context context){
        this.context=context;
        defaultExceptionHander=Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        if(!handleEcxception(e)&&defaultExceptionHander!=null){
            //未處理交由系統處理
            defaultExceptionHander.uncaughtException(t,e);
        }else {
            //已處理結束進程
            Process.killProcess(Process.myPid());
            System.exit(1);
        }
    }


    private boolean handleEcxception(Throwable ex){
        if(ex == null){
            return false;
        }
        //記錄設備信息,異常
        SaveDeviceInfo(ex);
        return true;
    }

    private void SaveDeviceInfo(Throwable ex) {
        //獲取異常類型
        String info=ex.toString();
        Log.e("info","-->"+info);
        StackTraceElement[] stackTraceElement=ex.getStackTrace();
        //獲取異常具體發送行號
        for (StackTraceElement error:stackTraceElement) {
            Log.e("error","-->"+error.toString());
        }
        //獲取設備信息,系統版本,手機品牌
        String brand=Build.BRAND;       //品牌
        String model=Build.MODEL;       //型號
        int SDK=Build.VERSION.SDK_INT;  //獲取系統版本
        Log.e("INFO","brand:"+brand+" model:"+model+" SDK:"+SDK);
        //這兒自己保存相關異常信息/發送異常到後臺服務器

    }
}

好了異常捕捉類定義完成,只要在Application中初始化就可以了

ExceptionCapture exceptionCapture=ExceptionCapture.getInstance();
exceptionCapture.init(this);

這樣就可以捕捉全局異常了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章