Android把okhttp的返回数据放在主线程处理(切换线程)

public abstract class HttpCallBack implements Callback {

    public abstract void onSuccess(String data,T body);

    public abstract void onFailure(String data);
    
    Handler mainHandler = new Handler(MyApp.getContext().getMainLooper());

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        if(response != null && response.isSuccessful()){
            String a=response.body().string();
            Class c = getClass();

            Type type = c.getGenericSuperclass();

            type = ((ParameterizedType) type).getActualTypeArguments()[0];
            String res = new String(a.getBytes());

            final T body = JSON.parseObject(res, type);//JsonParseUtils.fromJson(response, type);
            mainHandler.post(new Runnable() {
                @Override
                public void run() {
                    onSuccess(null, body);
                }
            });
        }else{
            final String body = response.body().string();
            XLog.i("body:"+body);
            mainHandler.post(new Runnable() {
                @Override
                public void run() {
                    onFailure(body);
                }
            });
        }
    }

}
    }

}

你可能感兴趣的:(Android把okhttp的返回数据放在主线程处理(切换线程))