学无先后,达者为师

网站首页 编程语言 正文

Kotlin全局捕捉协程异常方法详解_Android

作者:安果移不动   更新时间: 2022-10-23 编程语言

单个异常捕捉

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

点击按钮后程序会闪退

但是

异常可以拿到。这就很好了

原文链接:https://blog.csdn.net/mp624183768/article/details/126458290

栏目分类
最近更新