1page.title=Setting Up a RequestQueue 2 3trainingnavtop=true 4 5@jd:body 6 7<div id="tb-wrapper"> 8<div id="tb"> 9 10<!-- table of contents --> 11<h2>This lesson teaches you to</h2> 12<ol> 13 <li><a href="#network">Set Up a Network and Cache</a></li> 14 <li><a href="#singleton">Use a Singleton Pattern</a></li> 15</ol> 16 17</div> 18</div> 19 20<a class="notice-developers-video wide" href="https://www.youtube.com/watch?v=yhv8l9F44qo"> 21<div> 22 <h3>Video</h3> 23 <p>Volley: Easy, Fast Networking for Android</p> 24</div> 25</a> 26 27 28<p>The previous lesson showed you how to use the convenience method 29<code>Volley.newRequestQueue</code> to set up a {@code RequestQueue}, taking advantage of 30Volley's default behaviors. This lesson walks you through the explicit steps of creating a 31{@code RequestQueue}, to allow you to supply your own custom behavior.</p> 32 33<p>This lesson also describes the recommended practice of creating a {@code RequestQueue} 34as a singleton, which makes the {@code RequestQueue} last the lifetime of your app.</p> 35 36<h2 id="network">Set Up a Network and Cache</h2> 37 38<p>A {@code RequestQueue} needs two things to do its job: a network to perform transport 39of the requests, and a cache to handle caching. There are standard implementations of these 40available in the Volley toolbox: {@code DiskBasedCache} provides a one-file-per-response 41cache with an in-memory index, and {@code BasicNetwork} provides a network transport based 42on your preferred HTTP client.</p> 43 44<p>{@code BasicNetwork} is Volley's default network implementation. A {@code BasicNetwork} 45must be initialized with the HTTP client your app is using to connect to the network. 46Typically this is an {@link java.net.HttpURLConnection}.</p> 47 48<p>This snippet shows you the steps involved in setting up a 49{@code RequestQueue}:</p> 50 51<pre> 52RequestQueue mRequestQueue; 53 54// Instantiate the cache 55Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap 56 57// Set up the network to use HttpURLConnection as the HTTP client. 58Network network = new BasicNetwork(new HurlStack()); 59 60// Instantiate the RequestQueue with the cache and network. 61mRequestQueue = new RequestQueue(cache, network); 62 63// Start the queue 64mRequestQueue.start(); 65 66String url ="http://www.example.com"; 67 68// Formulate the request and handle the response. 69StringRequest stringRequest = new StringRequest(Request.Method.GET, url, 70 new Response.Listener<String>() { 71 @Override 72 public void onResponse(String response) { 73 // Do something with the response 74 } 75}, 76 new Response.ErrorListener() { 77 @Override 78 public void onErrorResponse(VolleyError error) { 79 // Handle error 80 } 81}); 82 83// Add the request to the RequestQueue. 84mRequestQueue.add(stringRequest); 85 86// ... 87</pre> 88 89<p>If you just need to make a one-time request and don't want to leave the thread pool 90around, you can create the {@code RequestQueue} wherever you need it and call {@code stop()} on the 91{@code RequestQueue} once your response or error has come back, using the 92{@code Volley.newRequestQueue()} method described in <a href="simple.html">Sending a Simple 93Request</a>. But the more common use case is to create the {@code RequestQueue} as a 94singleton to keep it running for the lifetime of your app, as described in the next section.</p> 95 96 97<h2 id="singleton">Use a Singleton Pattern</h2> 98 99<p>If your application makes constant use of the network, it's probably most efficient to 100set up a single instance of {@code RequestQueue} that will last the lifetime of your app. 101You can achieve this in various ways. The recommended approach is to implement a singleton 102class that encapsulates {@code RequestQueue} and other Volley 103functionality. Another approach is to subclass {@link android.app.Application} and set up the 104{@code RequestQueue} in {@link android.app.Application#onCreate Application.onCreate()}. 105But this approach is <a href="{@docRoot}reference/android/app/Application.html"> 106discouraged</a>; a static singleton can provide the same functionality in a more modular 107way. </p> 108 109<p>A key concept is that the {@code RequestQueue} must be instantiated with the 110{@link android.app.Application} context, not an {@link android.app.Activity} context. This 111ensures that the {@code RequestQueue} will last for the lifetime of your app, instead of 112being recreated every time the activity is recreated (for example, when the user 113rotates the device). 114 115<p>Here is an example of a singleton class that provides {@code RequestQueue} and 116{@code ImageLoader} functionality:</p> 117 118<pre>public class MySingleton { 119 private static MySingleton mInstance; 120 private RequestQueue mRequestQueue; 121 private ImageLoader mImageLoader; 122 private static Context mCtx; 123 124 private MySingleton(Context context) { 125 mCtx = context; 126 mRequestQueue = getRequestQueue(); 127 128 mImageLoader = new ImageLoader(mRequestQueue, 129 new ImageLoader.ImageCache() { 130 private final LruCache<String, Bitmap> 131 cache = new LruCache<String, Bitmap>(20); 132 133 @Override 134 public Bitmap getBitmap(String url) { 135 return cache.get(url); 136 } 137 138 @Override 139 public void putBitmap(String url, Bitmap bitmap) { 140 cache.put(url, bitmap); 141 } 142 }); 143 } 144 145 public static synchronized MySingleton getInstance(Context context) { 146 if (mInstance == null) { 147 mInstance = new MySingleton(context); 148 } 149 return mInstance; 150 } 151 152 public RequestQueue getRequestQueue() { 153 if (mRequestQueue == null) { 154 // getApplicationContext() is key, it keeps you from leaking the 155 // Activity or BroadcastReceiver if someone passes one in. 156 mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext()); 157 } 158 return mRequestQueue; 159 } 160 161 public <T> void addToRequestQueue(Request<T> req) { 162 getRequestQueue().add(req); 163 } 164 165 public ImageLoader getImageLoader() { 166 return mImageLoader; 167 } 168}</pre> 169 170<p>Here are some examples of performing {@code RequestQueue} operations using the singleton 171class:</p> 172 173<pre> 174// Get a RequestQueue 175RequestQueue queue = MySingleton.getInstance(this.getApplicationContext()). 176 getRequestQueue(); 177 178// ... 179 180// Add a request (in this example, called stringRequest) to your RequestQueue. 181MySingleton.getInstance(this).addToRequestQueue(stringRequest); 182</pre> 183