全局異常捕獲 UncaughtExceptionHandler
當app上線后,可能存在某些異常導致程序崩潰,開發(fā)者不能及時獲取到底哪里出問題。所以在開發(fā)過程中,接入了第三方Crash分析平臺比如Bugly、bugtags等。其實我們也可以很簡單的實現(xiàn)全局異常處理。
未捕獲異常大多發(fā)生在在多線程環(huán)境中,子線程拋出的異常是不能用主線程中try….catch捕獲??梢越o線程設置UncaughtExceptionHandler,當出現(xiàn)異常時會回調(diào)UncaughtExceptionHandler中的uncaughtException(Thread t, Throwable e) 方法。
// 全局所有線程設置
Thread.setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler handler);
// 指定線程設置
thread.setUncaughtExceptionHandler( UncaughtExceptionHandler handler);
class CrashHandler : Thread.UncaughtExceptionHandler {
/**
* 單例對象
*/
companion object {
val Instance by lazy { CrashHandler() }
}
private lateinit var mContext: Context
override fun uncaughtException(t: Thread?, e: Throwable?) {
// todo 自己處理異常邏輯,服務端上包、存本地log、彈出彈窗等
}
/**
* 在Application 中進行全局初始化
*/
fun init(context: Context) {
mContext = context
Thread.setDefaultUncaughtExceptionHandler(this)
}
}