我可以做一个凌空同步请求?做一个

由网友(夏日么么凉)分享简介:想象一下,我在这已经有一个后台线程服务。我可以做在同一个线程使用凌空一个请求,这样的回调同步发生?Imagine I'm in a Service that already has a background thread. Can I do a request using volley in that same th...

想象一下,我在这已经有一个后台线程服务。我可以做在同一个线程使用凌空一个请求,这样的回调同步发生?

Imagine I'm in a Service that already has a background thread. Can I do a request using volley in that same thread, so that callbacks happen synchronously?

有2方面的原因: - 首先,我并不需要另一个线程,这将是一种浪费创建它。 - 其次,如果我在ServiceIntent,该线程的执行将完成回调之前,并为此我不会有任何的凌空回应。我知道我可以创建自己的服务有一个runloop我可以控制一些线索,但希望有在凌空此功能。

There are 2 reasons for this: - First, I do not need another thread and it would be a waste to create it. - Second, if I'm in a ServiceIntent, the execution of the thread will finish before the callback, and therefor I will have no response from Volley. I know I can create my own Service that has some thread with a runloop I can control, but it would be desirable having this functionality in volley.

感谢您!

推荐答案

它看起来像有可能与排球的 RequestFuture 类。例如,创建一个同步的JSON HTTP GET请求,您可以执行以下操作:

It looks like it is possible with Volley's RequestFuture class. For example, to create a synchronous JSON HTTP GET request, you can do the following:

RequestFuture<JSONObject> future = RequestFuture.newFuture();
JsonObjectRequest request = new JsonObjectRequest(URL, null, future, future);
requestQueue.add(request);

它总是会阻止,你可以使用的Future.get(30 TimeUnit.SECONDS); 之后,那个时候它会抛出超时异常,而不是无限期地等待

it will always block you can use future.get(30, TimeUnit.SECONDS); after that time it will throw timeout exception rather than waiting indefinitely

try {
  JSONObject response = future.get(); // this will block (forever)
} catch (InterruptedException e) {
  // exception handling
} catch (ExecutionException e) {
  // exception handling
}
阅读全文

相关推荐

最新文章