请求队列在 Android

RequestQueue In Android

我对发送简单请求文档中提供的代码有疑问。

 val queue = Volley.newRequestQueue(this)
val url = "https://www.google.com"

// Request a string response from the provided URL.
val stringRequest = StringRequest(Request.Method.GET, url,
        Response.Listener<String> { response ->
            // Display the first 500 characters of the response string.
            textView.text = "Response is: ${response.substring(0, 500)}"
        },
        Response.ErrorListener { textView.text = "That didn't work!" })

// Add the request to the RequestQueue.
queue.add(stringRequest)

在此代码中,首先向 url 发出请求,然后将 stringRequest 存储在队列中。我的疑问是,在发出请求时我们会得到响应,那么将它存储在队列中然后重新运行所有操作(如检查缓存内存等)的需要是什么

通过以下语句,您可以告诉运行时您想要发出什么样的请求。

val stringRequest = StringRequest(Request.Method.GET, url,
    Response.Listener<String> { response ->
        // Display the first 500 characters of the response string.
        textView.text = "Response is: ${response.substring(0, 500)}"
    },
    Response.ErrorListener { textView.text = "That didn't work!" })

请求不会立即执行。为了让它被执行,它必须被添加到请求队列中。

换句话说:如果您删除以下行

queue.add(stringRequest)

根本不会提出请求。

guide on Volley 中的这些行总结了它的工作原理(强调我的)

To send a request, you simply construct one and add it to the RequestQueue with add(), as shown above. Once you add the request it moves through the pipeline, gets serviced, and has its raw response parsed and delivered.