gpt4 book ai didi

android - 其他线程中的 Volley 响应

转载 作者:太空狗 更新时间:2023-10-29 14:01:00 24 4
gpt4 key购买 nike

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

最佳答案

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

关于android - 其他线程中的 Volley 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35538160/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com