Crash

记录一下之前搞的异常捕获问题

Android 全局异常捕获类

public class NeverCrash {
    private CrashHandler mCrashHandler;

    private static NeverCrash mInstance;

    private NeverCrash() {

    }

    private static NeverCrash getInstance() {
        if (mInstance == null) {
            synchronized (NeverCrash.class) {
                if (mInstance == null) {
                    mInstance = new NeverCrash();
                }
            }
        }

        return mInstance;
    }

    public static void init(CrashHandler crashHandler) {
        getInstance().setCrashHandler(crashHandler);
    }



    private void setCrashHandler(CrashHandler crashHandler) {
        mCrashHandler = crashHandler;
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                for (; ; ) {
                    try {
                        Looper.loop();
                    } catch (Throwable e) {
                        if (mCrashHandler != null) {//捕获异常处理
                            mCrashHandler.uncaughtException(Looper.getMainLooper().getThread(), e);
                        }
                    }
                }
            }
        });

        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                if (mCrashHandler != null) {//捕获异常处理
                    mCrashHandler.uncaughtException(t, e);
                }
            }
        });

    }

    public interface CrashHandler {
        void uncaughtException(Thread t, Throwable e);
    }
}

 

使用方法 在application里调用

NeverCrash.init(this);  

实现

 NeverCrash.CrashHandler接口 在实现的方法里面实现对应的操作 

@Override
public void uncaughtException(Thread t, Throwable e) {
    Log.d("TAG", Log.getStackTraceString(e));
    showToast(e.getMessage()+"\n"+Log.getStackTraceString(e));
}

你可能感兴趣的:(Crash)