Kotlin全局捕捉協(xié)程異常方法詳解
單個異常捕捉
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類里面 隨便找個位置創(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
我們可以確定這個文件的路徑為
com.example.coroutine.GlobalCoroutineExceptionHandler
寫到剛才創(chuàng)建的沒有后綴的文件當中去

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

異??梢阅玫?。這就很好了
到此這篇關(guān)于Kotlin全局捕捉協(xié)程異常方法詳解的文章就介紹到這了,更多相關(guān)Kotlin協(xié)程異常內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Android滑動優(yōu)化高仿QQ6.0側(cè)滑菜單(滑動優(yōu)化)
之前的實現(xiàn)只是簡單的可以顯示和隱藏左側(cè)的菜單,但是特別生硬,而且沒有任何平滑的趨勢,那么今天就來優(yōu)化一下吧,加上平滑效果,而且可以根據(jù)手勢滑動的方向來判斷是否是顯示和隱藏2016-02-02
android ItemTouchHelper實現(xiàn)可拖拽和側(cè)滑的列表的示例代碼
本篇文章主要介紹了ItemTouchHelper實現(xiàn)可拖拽和側(cè)滑的列表的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-02-02
Android 實現(xiàn)帶角標的ImageView(微博,QQ消息提示)
下面小編就為大家分享一篇Android 實現(xiàn)帶角標的ImageView(微博,QQ消息提示),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-01-01
Android垃圾回收機制及程序優(yōu)化System.gc
這篇文章主要介紹了Android垃圾回收機制及程序優(yōu)化System.gc的相關(guān)資料,需要的朋友可以參考下2016-01-01

