目錄
- 簡介
- XJB 代碼
- 用法
簡介
UncaughtExceptionHandler
是一個接口懂更,通過它可以捕獲并處理在一個線程對象中拋出的未檢測到的異常急膀,避免程序奔潰。
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
皂股,通過
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() {
}
}