NetworkOnMainThreadException 尝试在 UI 线程上 运行 okhttp 响应代码

NetworkOnMainThreadException when trying to run okhttp response code on UI thread

在我的 Android 应用程序中,我使用 AppAuth 通过 OpenID 连接端点对用户进行身份验证,因此我进行了一系列异步调用和当最后一个 returns 时,我正在使用 okhttp 获取最终结果,我想在 activity 的 UI 中显示它,如下所示:

authService.performTokenRequest(
    authResponse.createTokenExchangeRequest()
) { tokenResponse: TokenResponse?, tokenException: AuthorizationException? ->
    if (tokenResponse != null) {                         
        authState.performActionWithFreshTokens(authService) { accessToken, _, ex ->
            if (accessToken != null) {
                val url = ...
                val request = ...
                http.newCall(request).enqueue(object: Callback {
                    override fun onFailure(call: Call?, e: IOException?) {...}
                    override fun onResponse(call: Call?, response: Response?) {
                        if (response != null) {
                            this@MainActivity.runOnUiThread {
                                textView.text = response.body()!!.string()
                            }
                        }
                    }
                })
            }
        }
    }
}

但是当我尝试更新我的文本视图时,出现以下异常:

android.os.NetworkOnMainThreadException

当我尝试删除 runOnUiThread 时,我收到另一个异常:“只有创建视图层次结构的原始线程才能触及它的视图”

我不明白。我该怎么办?

这应该有效:

override fun onResponse(call: Call?, response: Response?) {                           
    val body = response?.body()?.string()
    this@MainActivity.runOnUiThread { textView.text = body }              
}

您不应在 UI 线程上访问 response,因为它被视为 IO 操作。