Volley HTTP库系列教程(2)Volley.newRequestQueue示例,发请求的流程,取消请求
1.This lesson teaches you to
- Add the INTERNET Permission
- Use newRequestQueue Volley.newRequestQueue示例
- Send a Request RequestQueue发送请求的流程
- Cancel a Request 如何取消正在运行的请求,以及取消所有tag为xx的请求
VIDEO
Volley: Easy, Fast Networking for Android
At a high level, you use Volley by creating a RequestQueue
and passing it Request
objects. The RequestQueue
manages worker threads for running the network operations, reading from and writing to the cache, and parsing responses. Requests do the parsing of raw responses and Volley takes care of dispatching the parsed response back to the main thread for delivery.
This lesson describes how to send a request using theVolley.newRequestQueue
convenience method, which sets up a RequestQueue
for you. See the next lesson, Setting Up a RequestQueue, for information on how to set up aRequestQueue
yourself.
This lesson also describes how to add a request to aRequestQueue
and cancel a request.
2.Add the INTERNET Permission
To use Volley, you must add the android.permission.INTERNET
permission to your app's manifest. Without this, your app won't be able to connect to the network.
3.Use newRequestQueue
Volley provides a convenience method Volley.newRequestQueue
that sets up a RequestQueue
for you, using default values, and starts the queue. For example:
1 final TextView mTextView = (TextView) findViewById(R.id.text); 2 ... 3 4 // Instantiate the RequestQueue. 5 RequestQueue queue = Volley.newRequestQueue(this); 6 String url ="http://www.google.com"; 7 8 // Request a string response from the provided URL. 9 StringRequest stringRequest = new StringRequest(Request.Method.GET, url, 10 new Response.Listener<String>() { 11 @Override 12 public void onResponse(String response) { 13 // Display the first 500 characters of the response string. 14 mTextView.setText("Response is: "+ response.substring(0,500)); 15 } 16 }, new Response.ErrorListener() { 17 @Override 18 public void onErrorResponse(VolleyError error) { 19 mTextView.setText("That didn't work!"); 20 } 21 }); 22 // Add the request to the RequestQueue. 23 queue.add(stringRequest);
Volley always delivers parsed responses on the main thread. Running on the main thread is convenient for populating UI controls with received data, as you can freely modify UI controls directly from your response handler, but it's especially critical to many of the important semantics provided by the library, particularly related to canceling requests.
See Setting Up a RequestQueue for a description of how to set up a RequestQueue
yourself, instead of using the Volley.newRequestQueue
convenience method.
4.Send a Request
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.
先从线程池,唤起一个线程,如果本地缓存可以服务,那么就返回数据,不可以就发出请求.然后将返回数据写入到缓存,解析数据并传给UI线程.
When you call add()
, Volley runs one cache processing thread and a pool of network dispatch threads. When you add a request to the queue, it is picked up by the cache thread and triaged: if the request can be serviced from cache, the cached response is parsed on the cache thread and the parsed response is delivered on the main thread. If the request cannot be serviced from cache, it is placed on the network queue. The first available network thread takes the request from the queue, performs the HTTP transaction, parsse the response on the worker thread, writes the response to cache, and posts the parsed response back to the main thread for delivery.
Note that expensive operations like blocking I/O and parsing/decoding are done on worker threads. You can add a request from any thread, but responses are always delivered on the main thread.
Figure 1 illustrates the life of a request:

Figure 1. Life of a request.
5.Cancel a Request
To cancel a request, call cancel()
on your Request
object. Once cancelled, Volley guarantees that your response handler will never be called. What this means in practice is that you can cancel all of your pending requests in your activity's onStop()
method and you don't have to litter your response handlers with checks forgetActivity() == null
, whether onSaveInstanceState()
has been called already, or other defensive boilerplate.
To take advantage of this behavior, you would typically have to track all in-flight requests in order to be able to cancel them at the appropriate time. There is an easier way: you can associate a tag object with each request. You can then use this tag to provide a scope of requests to cancel. For example, you can tag all of your requests with the Activity
they are being made on behalf of, and call requestQueue.cancelAll(this)
fromonStop()
. Similarly, you could tag all thumbnail image requests in a ViewPager
tab with their respective tabs and cancel on swipe to make sure that the new tab isn't being held up by requests from another one.
Here is an example that uses a string value for the tag:
- Define your tag and add it to your requests.
1 public static final String TAG = "MyTag"; 2 StringRequest stringRequest; // Assume this exists. 3 RequestQueue mRequestQueue; // Assume this exists. 4 5 // Set the tag on the request. 6 stringRequest.setTag(TAG); 7 8 // Add the request to the RequestQueue. 9 mRequestQueue.add(stringRequest);
- In your activity's
onStop()
method, cancel all requests that have this tag.1 @Override 2 protected void onStop () { 3 super.onStop(); 4 if (mRequestQueue != null) { 5 mRequestQueue.cancelAll(TAG); 6 } 7 }
Take care when canceling requests. If you are depending on your response handler to advance a state or kick off another process, you need to account for this. Again, the response handler will not be called.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?