在应用开发过程中,当手机出货后应用使用过程中出现的一些比较严重的问题(如crash、anr)开发人员无法得知,从而无法进行相关的维护。下面给出一种常用解决方案:
1.应用层crash捕获方案
对于crash异常比较好处理,在java语言中可以通过实现UncaughtExceptionHandler去自定义处理未被应用自身catch的exception,相关代码如下:
@SuppressLint("StaticFieldLeak")
class CrashHandler private constructor() : Thread.UncaughtExceptionHandler {
private lateinit var context: Context
private val path: String = Environment.getExternalStorageDirectory().path + "/bugly/log/"
private val defaultCrashHandler = Thread.getDefaultUncaughtExceptionHandler()
init {
Thread.setDefaultUncaughtExceptionHandler(this)
}
private fun init(context: Context) {
this.context = context.applicationContext
}
override
fun uncaughtException(thread: Thread, ex: Throwable) {
LogUtils.e(TAG, "uncaughtException thread ${thread.id},error ${ex.message}")
try {
dumpExceptionToExternalStorage(ex)
//todo upload exception to server
} catch (e: IOException) {
e.printStackTrace()
}
ex.printStackTrace()
defaultCrashHandler.uncaughtException(thread, ex)
}
private fun dumpExceptionToExternalStorage(ex: Throwable) {