【问题标题】:Volley response in Other thread其他线程中的凌空响应
【发布时间】:2016-06-02 23:10:24
【问题描述】:

我知道 volley 在其他线程中发送请求,但在 Main UI Thread 中处理响应。我想知道如何在其他线程中处理 Volley 的响应,或者我必须使用 Async Task 吗?提前致谢。

【问题讨论】:

  • 带着同样的问题来到这里,但显然唯一的方法是创建一个 AsyncTask

标签: android android-asynctask android-volley


【解决方案1】:

您可以在 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 线程上。如果要将响应传输到其他线程,则需要使用线程安全的共享变量并进行相应的同步。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-24
    • 2016-07-25
    • 2020-09-12
    • 1970-01-01
    • 2018-08-26
    • 2017-02-28
    • 1970-01-01
    相关资源
    最近更新 更多