gpt4 book ai didi

android - 主线程上的 Okhttp 响应回调

转载 作者:IT老高 更新时间:2023-10-28 13:23:16 31 4
gpt4 key购买 nike

我创建了一个帮助类来处理我的应用程序中的所有 http 调用。它是一个简单的 okhttp 单例包装器,看起来像这样(我省略了一些不重要的部分):

public class HttpUtil {

private OkHttpClient client;
private Request.Builder builder;

...

public void get(String url, HttpCallback cb) {
call("GET", url, cb);
}

public void post(String url, HttpCallback cb) {
call("POST", url, cb);
}

private void call(String method, String url, final HttpCallback cb) {
Request request = builder.url(url).method(method, method.equals("GET") ? null : new RequestBody() {
// don't care much about request body
@Override
public MediaType contentType() {
return null;
}

@Override
public void writeTo(BufferedSink sink) throws IOException {

}
}).build();

client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, Throwable throwable) {
cb.onFailure(null, throwable);
}

@Override
public void onResponse(Response response) throws IOException {
if (!response.isSuccessful()) {
cb.onFailure(response, null);
return;
}
cb.onSuccess(response);
}
});
}


public interface HttpCallback {

/**
* called when the server response was not 2xx or when an exception was thrown in the process
* @param response - in case of server error (4xx, 5xx) this contains the server response
* in case of IO exception this is null
* @param throwable - contains the exception. in case of server error (4xx, 5xx) this is null
*/
public void onFailure(Response response, Throwable throwable);

/**
* contains the server response
* @param response
*/
public void onSuccess(Response response);
}

}

然后,在我的主要 Activity 中,我使用这个助手类:

HttpUtil.get(url, new HttpUtil.HttpCallback() {
@Override
public void onFailure(Response response, Throwable throwable) {
// handle failure
}

@Override
public void onSuccess(Response response) {
// <-------- Do some view manipulation here
}
});

onSuccess 在代码运行时抛出异常:

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

据我了解,Okhttp 回调在主线程上运行,为什么会出现此错误?

** 顺便说一句,我创建了 HttpCallback 接口(interface)来包装 Okhttp 的 Callback 类,因为我想改变 onResponse 的行为> 和 onFailure 这样我就可以统一处理由于 i/o 异常导致的失败响应和由于服务器问题导致的失败响应的逻辑。

谢谢。

最佳答案

From my understanding, Okhttp callbacks run on the main thread so why do I get this error ?

这不是真的。回调在后台线程上运行。如果您想立即处理 UI 中的某些内容,则需要发布到主线程。

由于您已经有一个围绕回调的包装器,您可以在帮助器内部执行此操作,以便为方便起见在主线程上调用所有 HttpCallback 方法。

关于android - 主线程上的 Okhttp 响应回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24246783/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com