我可以用volley完成同步请求吗?假设我在一个已经有后台线程的服务中。我是否可以在同一个线程中使用volley执行请求,以便回调同步进行?这有两个原因:-首先,我不需要另一个线程,创建它将是一种浪费。-第二,如果我在ServiceIntent中,线程的执行将在回调之前完成,因此,我将不会得到volley的响应。我知道我可以创建我自己的服务,它有一个我可以控制的运行循环线程,但是在volley中使用这个功能是可取的。谢谢!
3 回答
RISEBY
TA贡献1856条经验 获得超5个赞
RequestFuture
RequestFuture<JSONObject> future = RequestFuture.newFuture();JsonObjectRequest request = new JsonObjectRequest(URL, new JSONObject(),
future, future);requestQueue.add(request);try {
JSONObject response = future.get(); // this will block} catch (InterruptedException e) {
// exception handling} catch (ExecutionException e) {
// exception handling}
翻翻过去那场雪
TA贡献2065条经验 获得超14个赞
get()future.get(30, TimeUnit.SECONDS)
try {
return future.get(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// exception handling
} catch (ExecutionException e) {
// exception handling
} catch (TimeoutException e) {
// exception handling
} /**
* Runs a blocking Volley request
*
* @param method get/put/post etc
* @param url endpoint
* @param errorListener handles errors
* @return the input stream result or exception: NOTE returns null once the onErrorResponse listener has been called
*/
public InputStream runInputStreamRequest(int method, String url, Response.ErrorListener errorListener) {
RequestFuture<InputStream> future = RequestFuture.newFuture();
InputStreamRequest request = new InputStreamRequest(method, url, future, errorListener);
getQueue().add(request);
try {
return future.get(REQUEST_TIMEOUT, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Log.e("Retrieve cards api call interrupted.", e);
errorListener.onErrorResponse(new VolleyError(e));
} catch (ExecutionException e) {
Log.e("Retrieve cards api call failed.", e);
errorListener.onErrorResponse(new VolleyError(e));
} catch (TimeoutException e) {
Log.e("Retrieve cards api call timed out.", e);
errorListener.onErrorResponse(new VolleyError(e));
}
return null;
}添加回答
举报
0/150
提交
取消
