UncaughtExceptionHandler

目录

  • 简介
  • XJB 代码
  • 用法

简介

UncaughtExceptionHandler 是一个接口,通过它可以捕获并处理在一个线程对象中抛出的未检测到的异常,避免程序奔溃。

XJB 代码

// CrashHandler 实现 UncaughtExceptionHandler 接口并且引用 HandleException 接口
public class CrashHandler implements Thread.UncaughtExceptionHandler {

    private static CrashHandler instance;
    private static final String TAG = "CrashHandler";
    private HandleException mHandleException = null;

    /**
     * Single instance, also get get the application context.
     */
    private CrashHandler() {
        super();
        Thread.setDefaultUncaughtExceptionHandler(this);
        Log.d(TAG, "CrashHandler: init");
    }

    /**
     * Handle uncaught exception here to make sure the application can work well forever.
     *
     * @param t Thread
     * @param e Throwable
     */
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        Log.d(TAG, "uncaughtException: Thread");
        Log.d(TAG, "uncaughtException: Throwable");
        if (mHandleException != null) {
            Log.d(TAG, "uncaughtException: Begin handling");
            mHandleException.handle();
        }
    }

    /**
     * @return Single instance
     */
    public static synchronized CrashHandler getInstance() {
        if (instance == null) {
            instance = new CrashHandler();
        }
        return instance;
    }

    /**
     * Handle exceptions
     *
     * @param mHandleException HandleException
     */
    public void setHandleException(HandleException mHandleException) {
        this.mHandleException = mHandleException;
    }
}
// HandleException 接口
public interface HandleException {
    void handle();
}

用法

需要在应用中的 Application 中初始化 CrashHandler,通过
setHandleException() 方法进行处理异常。例如:

/**
 * Created by Kobe on 2017/11/23.
 * Demo application
 */

public class App extends Application implements HandleException {
    @Override
    public void onCreate() {
        super.onCreate();
        CrashHandler ch = CrashHandler.getInstance();
        ch.setHandleException(this);
    }

// 处理异常
    @Override
    public void handle() {

    }
}

你可能感兴趣的:(UncaughtExceptionHandler)