5

我在使用RequestFuture排球类时遇到问题。实际上它只是停在wait(0); 在下面的 RequestFuture 类的 Function 内部,doGet()并且永远不会被唤醒,onResponse或者onErrorResponse我认为它应该唤醒。

private synchronized T doGet(Long timeoutMs)
        throws InterruptedException, ExecutionException, TimeoutException {
    if (mException != null) {
        throw new ExecutionException(mException);
    }

    if (mResultReceived) {
        return mResult;
    }

    if (timeoutMs == null) {
        wait(0);
    } else if (timeoutMs > 0) {
        wait(timeoutMs);
    }

    if (mException != null) {
        throw new ExecutionException(mException);
    }

    if (!mResultReceived) {
        throw new TimeoutException();
    }

    return mResult;
}

@Override
public boolean isCancelled() {
    if (mRequest == null) {
        return false;
    }
    return mRequest.isCanceled();
}

@Override
public synchronized boolean isDone() {
    return mResultReceived || mException != null || isCancelled();
}

@Override
public synchronized void onResponse(T response) {
    mResultReceived = true;
    mResult = response;
    notifyAll();
}

@Override
public synchronized void onErrorResponse(VolleyError error) {
    mException = error;
    notifyAll();
}

这就是我尝试在上面调用所有这些的方式。

    RequestFuture<JSONObject> future = RequestFuture.newFuture();
    JsonObjectRequest myReq = new JsonObjectRequest(Request.Method.POST, url, jsonObj, future, future);
    requestQueue.add(myReq);

    try {

        JSONObject response = future.get();
    } catch (InterruptedException e) {
        // handle the error
    } catch (ExecutionException e) {
        // handle the error
    }

我也尝试更换线路

requestQueue.add(myReq);

future.setRequest(requestQueue.add(myReq));

或者

future.setRequest(myReq);

这也没有帮助。

我已经尝试了一个普通的 Volley 请求,它使用这个参数工作得很好,所以这不应该是原因。我想问题是,该请求从未真正执行过,这就是为什么永远无法到达响应侦听器的原因。也尝试过requestQueue.start(),但没有改变任何事情。

我希望我能很好地解释我的问题,提前谢谢!

4

4 回答 4

6

向 get 方法添加超时将能够捕获错误,如果没有给出超时,则它将错误发送回主线程。因此,更改 JSONObject response = future.get();with JSONObject response = future.get(REQUEST_TIMEOUT, TimeUnit.SECONDS);应该可以解决问题并将其包装在 try catch 中以等待超时

于 2014-10-11T00:08:23.610 回答
3

解决了!

JSONObject 响应 = future.get();

始终在单独的线程中运行未来请求。它在主线程中不起作用。我在 IntentService 中运行 Future Request Call 并且它工作得很好。

快乐编码:)

于 2015-02-05T09:12:21.833 回答
0

您需要调用future.get()另一个线程。尝试将其包装在 AsyncTask 中。

查看源代码,它看起来像是RequestQueue启动了一长串调用以加载响应并最终以结束RequestFuture.onResponse(这反过来又调用notifyAll通知线程停止等待,正如您所提到的)。我认为问题在于,wait(0)链条RequestQueue都在 UI 线程中运行,所以当wait(0)被调用时,RequestQueue链条也在等待,所以onResponse永远不会被调用,这就是为什么那条线会挂起(因为 wait(0) 永远等待)。

于 2013-10-25T00:26:24.440 回答
0

除了 Blair 和 Farhan 的解决方案之外,将重试策略附加到请求也可以完成这项工作。

request.setRetryPolicy(new DefaultRetryPolicy(RETRY_TIME, RETRY_ATTEMPTS, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
于 2017-06-27T15:01:41.413 回答