android - Kotlin 协程 CalledFromWrongThreadException

标签 android kotlin coroutine

我正在尝试使用 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/

相关文章:

API 11 之前的 View.getX() 的 Android 等效解决方法?

android - 非空字段在 Glide 中为空

android - 使用 Kotlin 在 Android Studio 中将 URI 的内容转换为 ByteArray

python - Tornado 上下文管理器在 gen.coroutine 中调用

c - alloca() 和 setjmp 的作用是什么?

java - java/android中的不同日期

android - 如何在android中对RecyclerView项目进行排序

android - 亚马逊火灾远程影响后台进程

android - Clean Architecture 和 Paging 3.0 with Room

c++ - makecontext()/swapcontext() 函数是否与 C++ 兼容