我正在尝试使用 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
函数将您的“繁重工作”显式卸载到后台线程中,如下所示:
// 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 线程中运行接触 View 或其他 UI 对象的协程:
launch(UI) {
val images = getImages(galleryPath)
imageListAdapter.setItems(images)
}
关于android - Kotlin 协程 CalledFromWrongThreadException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47072967/