【发布时间】:2016-06-02 23:10:24
【问题描述】:
我知道 volley 在其他线程中发送请求,但在 Main UI Thread 中处理响应。我想知道如何在其他线程中处理 Volley 的响应,或者我必须使用 Async Task 吗?提前致谢。
【问题讨论】:
-
带着同样的问题来到这里,但显然唯一的方法是创建一个 AsyncTask
标签: android android-asynctask android-volley
我知道 volley 在其他线程中发送请求,但在 Main UI Thread 中处理响应。我想知道如何在其他线程中处理 Volley 的响应,或者我必须使用 Async Task 吗?提前致谢。
【问题讨论】:
标签: android android-asynctask android-volley
您可以在 volley 的 RequestFuture 的帮助下发出阻止请求来做到这一点。像这样:
Runnable blockingRequest = new Runnable() {
@Override
public void run() {
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
}
}
};
Thread n = new Thread(blockingRequest);
n.start();
正如您所见,阻塞的响应将保留在同一个线程上,而不是 UI 线程上。如果要将响应传输到其他线程,则需要使用线程安全的共享变量并进行相应的同步。
【讨论】: