引入一个超级牛逼的崩溃拦截库
Application里面具体实现:
class MyApplication : Application() {
companion object {
lateinit var instance: MyApplication
}
override fun onCreate() {
super.onCreate()
instance = this
}
override fun attachBaseContext(base: Context) {
super.attachBaseContext(base)
DefenseCrash.initialize(this)
DefenseCrash.install { thread, throwable, isSafeMode, isCrashInChoreographer ->
//thread: The crash happened’s thread.
//throwable: The Exception exactly is.
//isSafeMode: If application is allready crashed and we saved it that is mean you are in safe mode,
//that happens most of the time is your Main Looper is compromised by some errors and not going to normal,and we keep it runing that’s called safe mode.
//isCrashInChoreographer: If crash happend in OnMeasure/OnLayout/OnDraw it will case screen blank or some view not draw successfully
//If you got this true, we suggest you restart or finish the current Activity for good
//You can throw some throwables here and if you do that, will case VM got this throwable and shutdown your process.
//And you should do somting here such as:
Log.i("Exceptionhandler",
"thread:${thread.name} " +
"exception:${throwable.message} " +
"isCrashInChoreographer:$isCrashInChoreographer " +
"isSafeMode:$isSafeMode")
//throwable.printStackTrace()
//FirebaseCrashlytics.getInstance().recordException(throwable);
Thread {
writeExceptionFile(throwable.stackTraceToString())
}.start()
}
}
@Throws(IOException::class)
fun writeExceptionFile(message: String) {
val file = File(filesDir, System.currentTimeMillis().toString()+"catch.txt")
val fwriter = FileWriter(file)
fwriter.write(message)
fwriter.flush()
fwriter.close()
}
}