Volley HTTP库系列教程(3)自定义RequestQueue和编写单例RequestQueue示例

Setting Up a RequestQueue

VIDEO

  Volley: Easy, Fast Networking for Android

  The previous lesson showed you how to use the convenience method Volley.newRequestQueue to set up aRequestQueue, taking advantage of Volley's default behaviors.   This lesson walks you through the explicit steps of creating aRequestQueue, to allow you to supply your own custom behavior.

  This lesson also describes the recommended practice of creating a RequestQueue as a singleton, which makes theRequestQueue last the lifetime of your app.

2.Set Up a Network and Cache 

  RequestQueue需要网络连接和缓存才能工作.

  DiskBasedCache负责缓存

  BasicNetwork负责网络连接,可选 AndroidHttpClient,HttpURLConnection

  A RequestQueue needs two things to do its job: a network to perform transport of the requests, and a cache to handle caching. There are standard implementations of these available in the Volley toolbox: DiskBasedCacheprovides a one-file-per-response cache with an in-memory index, and BasicNetwork provides a network transport based on your choice of AndroidHttpClient or HttpURLConnection.

  BasicNetwork is Volley's default network implementation. A BasicNetwork must be initialized with the HTTP client your app is using to connect to the network. Typically this is AndroidHttpClient orHttpURLConnection:

  To create an app that runs on all versions of Android, you can check the version of Android the device is running and choose the appropriate HTTP client, for example:

复制代码
1 HttpStack stack;
2 ...
3 // If the device is running a version >= Gingerbread...
4 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
5     // ...use HttpURLConnection for stack.
6 } else {
7     // ...use AndroidHttpClient for stack.
8 }
9 Network network = new BasicNetwork(stack);
复制代码

  This snippet shows you the steps involved in setting up a RequestQueue:

复制代码
 1 RequestQueue mRequestQueue;
 2 
 3 // Instantiate the cache
 4 Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap
 5 
 6 // Set up the network to use HttpURLConnection as the HTTP client.
 7 Network network = new BasicNetwork(new HurlStack());
 8 
 9 // Instantiate the RequestQueue with the cache and network.
10 mRequestQueue = new RequestQueue(cache, network);
11 
12 // Start the queue
13 mRequestQueue.start();
14 
15 String url ="http://www.myurl.com";
16 
17 // Formulate the request and handle the response.
18 StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
19         new Response.Listener<String>() {
20     @Override
21     public void onResponse(String response) {
22         // Do something with the response
23     }
24 },
25     new Response.ErrorListener() {
26         @Override
27         public void onErrorResponse(VolleyError error) {
28             // Handle error
29     }
30 });
31 
32 // Add the request to the RequestQueue.
33 mRequestQueue.add(stringRequest);
34 ...
复制代码

  If you just need to make a one-time request and don't want to leave the thread pool around, you can create theRequestQueue wherever you need it and call stop() on the RequestQueue once your response or error has come back, using the Volley.newRequestQueue() method described in Sending a Simple Request. But the more common use case is to create the RequestQueue as a singleton to keep it running for the lifetime of your app, as described in the next section.

3.Use a Singleton Pattern

  If your application makes constant use of the network, it's probably most efficient to set up a single instance ofRequestQueue that will last the lifetime of your app. You can achieve this in various ways. The recommended approach is to implement a singleton class that encapsulates RequestQueue and other Volley functionality. Another approach is to subclass Application and set up the RequestQueue inApplication.onCreate(). But this approach is discouraged; a static singleton can provide the same functionality in a more modular way.

  A key concept is that the RequestQueue must be instantiated with the Application context, not anActivity context. This ensures that the RequestQueue will last for the lifetime of your app, instead of being recreated every time the activity is recreated (for example, when the user rotates the device).

  Here is an example of a singleton class that provides RequestQueue and ImageLoader functionality:

复制代码
 1 public class MySingleton {
 2     private static MySingleton mInstance;
 3     private RequestQueue mRequestQueue;
 4     private ImageLoader mImageLoader;
 5     private static Context mCtx;
 6 
 7     private MySingleton(Context context) {
 8         mCtx = context;
 9         mRequestQueue = getRequestQueue();
10 
11         mImageLoader = new ImageLoader(mRequestQueue,
12                 new ImageLoader.ImageCache() {
13             private final LruCache<String, Bitmap>
14                     cache = new LruCache<String, Bitmap>(20);
15 
16             @Override
17             public Bitmap getBitmap(String url) {
18                 return cache.get(url);
19             }
20 
21             @Override
22             public void putBitmap(String url, Bitmap bitmap) {
23                 cache.put(url, bitmap);
24             }
25         });
26     }
27 
28     public static synchronized MySingleton getInstance(Context context) {
29         if (mInstance == null) {
30             mInstance = new MySingleton(context);
31         }
32         return mInstance;
33     }
34 
35     public RequestQueue getRequestQueue() {
36         if (mRequestQueue == null) {
37             // getApplicationContext() is key, it keeps you from leaking the
38             // Activity or BroadcastReceiver if someone passes one in.
39             mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
40         }
41         return mRequestQueue;
42     }
43 
44     public <T> void addToRequestQueue(Request<T> req) {
45         getRequestQueue().add(req);
46     }
47 
48     public ImageLoader getImageLoader() {
49         return mImageLoader;
50     }
51 }
复制代码

  Here are some examples of performing RequestQueue operations using the singleton class:

// Get a RequestQueue
RequestQueue queue = MySingleton.getInstance(this.getApplicationContext()).
    getRequestQueue();
...

// Add a request (in this example, called stringRequest) to your RequestQueue.
MySingleton.getInstance(this).addToRequestQueue(stringRequest);

 

posted @   f9q  阅读(366)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?
点击右上角即可分享
微信分享提示