问题是您试图同步返回的值enqueue
,但是它是使用回调的异步方法,因此您无法做到这一点。您有2个选择:
大致如下所示:
public void RequestGR(LatLng start, LatLng end, final Callback<JSONArray> arrayCallback)
{
EndpointInterface loginService = ServiceAuthGenerator.createService(EndpointInterface.class);
Call<GR> call = loginService.getroutedriver();
call.enqueue(new Callback<GR>() {
@Override
public void onResponse(Response<GR> response , Retrofit retrofit)
{
JSONArray jsonArray_GR = response.body().getRoutes();
arrayCallback.onResponse(jsonArray_GR);
}
@Override
public void onFailure(Throwable t) {
// error handling? arrayCallback.onFailure(t)?
}
});
}
这种方法的警告是,它只会将异步内容推上一个新的台阶,这可能对您来说是个问题。
看起来像:
public BlockingQueue<JSONArray> RequestGR(LatLng start, LatLng end)
{
// You can create a final container object outside of your callback and then pass in your value to it from inside the callback.
final BlockingQueue<JSONArray> blockingQueue = new ArrayBlockingQueue<>(1);
EndpointInterface loginService = ServiceAuthGenerator.createService(EndpointInterface.class);
Call<GR> call = loginService.getroutedriver();
call.enqueue(new Callback<GR>() {
@Override
public void onResponse(Response<GR> response , Retrofit retrofit)
{
JSONArray jsonArray_GR = response.body().getRoutes();
blockingQueue.add(jsonArray_GR);
}
@Override
public void onFailure(Throwable t) {
}
});
return blockingQueue;
}
BlockingQueue<JSONArray> result = RequestGR(42,42);
JSONArray value = result.take(); // this will block your thread
我强烈建议您阅读类似rxJava的框架。