我可以做一个凌空同步请求? [英] Can I do a synchronous request with volley?

查看:182
本文介绍了我可以做一个凌空同步请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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
}

这篇关于我可以做一个凌空同步请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆