val handler = coroutineexceptionhandler { coroutinecontext, throwable -> log.d(tag, "oncreate: handler${throwable}") } log.d(tag, "oncreate:1") findviewbyid<button>(r.id.button).also { it.setonclicklistener { globalscope.launch(handler) { log.d(tag, "oncreate: onclick") "anc".substring(10) } } }
launch里面如果不写handler
可以使用这样的方式来创建全局异常捕获处理
在main目录下
新建 resources\meta-inf\services\kotlinx.coroutines.coroutineexceptionhandler
注意没有后缀哦
然后回到java类里面 随便找个位置创建class类
内容
package com.example.coroutine import android.util.log import kotlinx.coroutines.coroutineexceptionhandler import kotlin.coroutines.coroutinecontext class globalcoroutineexceptionhandler : coroutineexceptionhandler { override val key = coroutineexceptionhandler private val tag = "globalcortineexceptionh" override fun handleexception(context: coroutinecontext, exception: throwable) { log.d(tag, "handleexception:${exception} ") } }
根据包名和类目
package com.example.coroutine.
globalcoroutineexceptionhandler
我们可以确定这个文件的路径为
com.example.coroutine.globalcoroutineexceptionhandler
写到刚才创建的没有后缀的文件当中去
程序里删除 hander
findviewbyid<button>(r.id.button).also { it.setonclicklistener { globalscope.launch { log.d(tag, "oncreate: onclick") "anc".substring(10) } } }
点击按钮后程序会闪退
但是
异常可以拿到。这就很好了
到此这篇关于kotlin全局捕捉协程异常方法详解的文章就介绍到这了,更多相关kotlin协程异常内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!