kotlin下 “android.os.NetworkOnMainThreadException” 或 “Only the original thread that created a view hierarchy can touch its views” 解决

 开发  kotlin下 “android.os.NetworkOnMainThreadException” 或 “Only the original thread that created a view hierarchy can touch its views” 解决已关闭评论
9月 272020
 

kotlin下使用协程时,出现错误提示android.os.NetworkOnMainThreadException 或 Only the original thread that created a view hierarchy can touch its views, 可以使用下面的方法解决:

 

1. 使用协程需build.gradle先加入

dependencies {

implementation “org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.9”
}

 

2.  套用下面的模版:

GlobalScope.launch {
    //TODO("Background processing...")
    withContext(Dispatchers.Main) {
        // TODO("Update UI here!")
    }
    TODO("Continue background processing...")
}