其他分享
首页 > 其他分享> > 超级简单Android 拦截app崩溃,并且把崩溃写入本地保存文件

超级简单Android 拦截app崩溃,并且把崩溃写入本地保存文件

作者:互联网

引入一个超级牛逼的崩溃拦截库

地址:https://github.com/xuuhaoo/Android-DefenseCrash/blob/main/README_CN.mdicon-default.png?t=L9C2https://github.com/xuuhaoo/Android-DefenseCrash/blob/main/README_CN.md

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()
    }

}

标签:DefenseCrash,isCrashInChoreographer,thread,app,isSafeMode,fwriter,throwable,崩溃,A
来源: https://blog.csdn.net/u010368726/article/details/121081106