Kotlin 协程 CalledFromWrongThreadException

Kotlin coroutines CalledFromWrongThreadException

我正在尝试使用 Kotlin 协程在后台完成一些繁重的工作 运行。

但是我收到了这个错误信息,

'android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.'

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

如何在后台正确设置运行?

我建议通过以下方式解决它:

首先,使用 withContext 函数将 "heavy job" 显式卸载到后台线程中,如下所示:

// 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
    ...
}

然后,总是 运行 触及 UI 线程中的视图或其他 UI 对象的协程:

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