Kotlin全局捕捉協(xié)程異常方法詳解
單個(gè)異常捕捉
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
可以使用這樣的方式來創(chuàng)建全局異常捕獲處理
在main目錄下
新建 resources\META-INF\services\kotlinx.coroutines.CoroutineExceptionHandler

注意沒有后綴哦
然后回到j(luò)ava類里面 隨便找個(gè)位置創(chuàng)建class類

內(nèi)容
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} ")
}
}根據(jù)包名和類目
package com.example.coroutine.
GlobalCoroutineExceptionHandler
我們可以確定這個(gè)文件的路徑為
com.example.coroutine.GlobalCoroutineExceptionHandler
寫到剛才創(chuàng)建的沒有后綴的文件當(dāng)中去

程序里刪除 hander
findViewById<Button>(R.id.button).also {
it.setOnClickListener {
GlobalScope.launch {
Log.d(TAG, "onCreate: onClick")
"anc".substring(10)
}
}
}點(diǎn)擊按鈕后程序會(huì)閃退
但是

異??梢阅玫?。這就很好了
到此這篇關(guān)于Kotlin全局捕捉協(xié)程異常方法詳解的文章就介紹到這了,更多相關(guān)Kotlin協(xié)程異常內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Flutter 底部彈窗如何實(shí)現(xiàn)多項(xiàng)選擇
在Flutter中提供了一個(gè)showModelBottomSheet方法用于彈出底部彈窗,本篇基于這個(gè)方法介紹實(shí)現(xiàn)底部彈窗多選的思路和方式。2021-06-06
Android ScrollView只能添加一個(gè)子控件問題解決方法
這篇文章主要介紹了Android ScrollView只能添加一個(gè)子控件問題解決方法,涉及Android界面布局的相關(guān)技巧,需要的朋友可以參考下2016-02-02
Android使用CoordinatorLayout實(shí)現(xiàn)底部彈出菜單
這篇文章主要為大家詳細(xì)介紹了Android使用CoordinatorLayout實(shí)現(xiàn)底部彈出菜單,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-11-11
Android Studio修改Log信息顏色的實(shí)現(xiàn)
這篇文章主要介紹了Android Studio修改Log信息顏色的實(shí)現(xiàn),具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04
Android學(xué)習(xí)之BottomSheetDialog組件的使用
BottomSheetDialog是底部操作控件,可在屏幕底部創(chuàng)建一個(gè)支持滑動(dòng)關(guān)閉視圖。本文將通過示例詳細(xì)講解它的使用,感興趣的小伙伴可以了解一下2022-06-06

