美文网首页
UncaughtExceptionHandler示例使用

UncaughtExceptionHandler示例使用

作者: 静水红阳 | 来源:发表于2021-01-31 17:07 被阅读0次

    概述

    UncaughtExceptionHandler是用来catch线程内的没有被捕获到的exception,可以在uncaughtException方法中对这些异常进行统一处理。

    用法

    UncaughtExceptionHandler是一个接口,需要我们手动去实现一个类,如下:

    class CrashHandler(var mContext: Context) : Thread.UncaughtExceptionHandler {
        var threadCrashHandler: Thread.UncaughtExceptionHandler? = null
        init {
            //获取系统默认的UncaughtException处理器
            threadCrashHandler = Thread.getDefaultUncaughtExceptionHandler()
            //设置该CrashHandler为程序的默认处理器
            Thread.setDefaultUncaughtExceptionHandler(this)
        }
    
        override fun uncaughtException(t: Thread, e: Throwable) {
    //        handleException(e)
            LogUtil.instance.d(t.name + "   " + e.message)
            //退出程序
            Process.killProcess(Process.myPid())
            exitProcess(1)
        }
    
        /**
         * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
         *
         * @param ex
         * @return true:如果处理了该异常信息;否则返回false.
         */
        private fun handleException(ex: Throwable?): Boolean {
            return true
        }
    
    
        companion object {
            fun newInstance(context: Context): CrashHandler {
                return CrashHandler(context)
            }
    
            const val TAG = "CrashHandler"
        }
    }
    

    我们实现UncaughtExceptionHandler接口并重写其中的uncaughtException方法以处理异常。

    相关文章

      网友评论

          本文标题:UncaughtExceptionHandler示例使用

          本文链接:https://www.haomeiwen.com/subject/ghurtltx.html