android多线程回调,android – Okhttp响应回调的主线程

我创建了一个帮助类来处理我的应用程序中的所有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);

}

}

然后,在我的主要活动,我使用这个帮助类:

HttpUtil.get(url, new HttpUtil.HttpCallback() {

@Override

public void onFailure(Response response, Throwable throwable) {

// handle failure

}

@Override

public void onSuccess(Response response) {

//

}

});

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

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the

original thread that created a view hierarchy can touch its views.

从我的理解,Okhttp回调运行在主线程,那么为什么我得到这个错误?

**作为一个侧面的注释,我创建了HttpCallback接口来包装Okhttp的Callback类,因为我想改变onResponse和onFailure的行为,所以我可以联合处理失败的响应的逻辑由于i / o异常和失败的响应,由于服务器问题。

谢谢。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值