简体   繁体   English

Kotlin协程CalledFromWrongThreadException

[英]Kotlin coroutines CalledFromWrongThreadException

I'm trying to use Kotlin coroutines to make some heavy job runs in the background. 我正在尝试使用Kotlin协程在后台进行一些繁重的工作。

But I got this error message, 但是我得到了这个错误信息,

'android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.' 'android.view.ViewRootImpl $ CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能触摸其视图。

fun setList() {
    media_image_list.adapter = imageListAdapter
    ...

    launch {
        val images = getImages(galleryPath)
        imageListAdapter.setItems(images)
    }
}




suspend private fun getImages(): MutableList<Image> {
    val uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
    ...
}

How to make it run in background correctly? 如何使其在后台正确运行?

I would suggest to address it in the following way: 我建议以以下方式解决此问题:

First, explicitly offload your "heavy job" into background threads using withContext function like this: 首先,使用withContext函数将“繁重的工作”显式卸载到后台线程中:

// explicitly request it to be executed in bg thread
suspend private fun getImages(): MutableList<Image> = withContext(CommonPool) {
    val uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
    ...
}

Then, always run the coroutines that touch the views or other UI objects in UI thread: 然后,始终运行在UI线程中触摸视图或其他UI对象的协程:

launch(UI) {
    val images = getImages(galleryPath)
    imageListAdapter.setItems(images)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM