日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

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

欄目分類
最近更新