Android 如何使用 Volley 网络请求队列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22106483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 05:31:37  来源:igfitidea点击:

How do I use the Volley network request queue?

androidandroid-volley

提问by CQM

I .add(new network calls to my Volley Request Queue which I have created as a singleton as suggested. But I always immediately .start()these network calls. This is always done as an action in an activity or a fragment.

我按照建议将.add(新网络调用到我已创建为单例的 Volley 请求队列。但我总是立即.start()拨打这些网络电话。这始终作为活动或片段中的操作完成。

The addmethod cannot even be chained into a startmethod, like .add(new volley request).start()

add方法甚至不能链接到一个start方法中,例如.add(new volley request).start()

So this assumes I am actually managing (or wanting to manage) a network queue somewhere, outside of the way Volley handles its queue, I guess. Should I be sending these things to an IntentService and listening for the IntentService to send a response back to my Fragment/Activity?

所以这假设我实际上正在某处管理(或想要管理)网络队列,我猜是在 Volley 处理其队列的方式之外。我应该将这些东西发送到 IntentService 并监听 IntentService 将响应发送回我的 Fragment/Activity 吗?

回答by vedant

If you create a requestQueueas:

如果您创建一个requestQueue

requestQueue = Volley.newRequestQueue(mAppContext);

you will not need start().

你不需要start().

According to docs of Volley.RequestQueue: "Creates a default instance of the worker pool and calls RequestQueue.start()on it."

根据以下文档Volley.RequestQueue:“创建工作池的默认实例并调用RequestQueue.start()它。”

Hence you can see why you never needed to call start()yourself.

因此你可以明白为什么你从来不需要给start()自己打电话。

However, if you create a requestQueueas (as shown in the official reference):

但是,如果您创建一个requestQueueas(如官方参考所示):

RequestQueue mRequestQueue;

// Instantiate the cache
Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap

// Set up the network to use HttpURLConnection as the HTTP client.
Network network = new BasicNetwork(new HurlStack());

// Instantiate the RequestQueue with the cache and network.
mRequestQueue = new RequestQueue(cache, network);

// Start the queue
mRequestQueue.start();

start()will have to be called.

start()将不得不被调用。

PS: I get the documentation as provided in the source code itself. IDEs are able to extract them effortlessly. I just hover over the method/class name whose document I need and press CTRL (in android-studio).

PS:我得到了源代码本身提供的文档。IDE 能够毫不费力地提取它们。我只是将鼠标悬停在我需要其文档的方法/类名称上,然后按 CTRL(在 android-studio 中)。

回答by Udi Oshi

As a volley user I can tell you that I have never called .start() method. all the requests i've added to the queue started automatically, I used singleton class like you did.

作为一个凌空用户,我可以告诉你,我从未调用过 .start() 方法。我添加到队列中的所有请求都会自动启动,我像您一样使用了单例类。