UncaughtExceptionHandler

目錄

  • 簡(jiǎn)介
  • XJB 代碼
  • 用法

簡(jiǎn)介

UncaughtExceptionHandler 是一個(gè)接口,通過(guò)它可以捕獲并處理在一個(gè)線(xiàn)程對(duì)象中拋出的未檢測(cè)到的異常,避免程序奔潰。

XJB 代碼

// CrashHandler 實(shí)現(xiàn) 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();
}

用法

需要在應(yīng)用中的 Application 中初始化 CrashHandler,通過(guò)
setHandleException() 方法進(jìn)行處理異常。例如:

/**
 * 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() {

    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容