use*_*475 4 android request android-volley
我在使用RequestFuture排球时遇到了问题.实际上它只是停在wait(0); 在doGet()下面的RequestFuture类中的函数内部,永远不会被我认为应该唤醒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();
}
Run Code Online (Sandbox Code Playgroud)
这是我尝试调用上述所有内容的方式.
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
}
Run Code Online (Sandbox Code Playgroud)
我也试过更换线
requestQueue.add(myReq);
同
future.setRequest(requestQueue.add(myReq));
要么
future.setRequest(myReq);
这也没有帮助.
我已经尝试过一个常用的Volley Request,它使用这个参数就可以了,所以这不应该是原因.我想问题是,请求永远不会被实际执行,这就是永远不会到达响应侦听器的原因.也尝试了requestQueue.start(),但没有改变一件事.
我希望我能很好地解释我的问题,提前谢谢!
小智 6
向get方法添加超时将提供捕获错误的能力,如果没有给出超时,则它将错误发送回主线程.因此,改变 JSONObject response = future.get();与 JSONObject response = future.get(REQUEST_TIMEOUT, TimeUnit.SECONDS);应该做的伎俩,敷在尝试捕捉的超时
您需要调用future.get()另一个线程。尝试将其包装在 AsyncTask 中。
查看源代码,它看起来像是RequestQueue启动了一长串调用来加载响应并最终结束RequestFuture.onResponse(这反过来调用notifyAll通知线程停止等待,正如您提到的)。我认为问题在于,wait(0)链RequestQueue都在 UI 线程中运行,所以当wait(0)被调用时,RequestQueue链也会等待,所以onResponse永远不会被调用,这就是为什么该行只是挂起(因为 wait(0) 永远等待)。