HttpStackstack;...// If the device is running a version >= Gingerbread...if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.GINGERBREAD){// ...use HttpURLConnection for stack.}else{// ...use AndroidHttpClient for stack.}Networknetwork=newBasicNetwork(stack);
RequestQueuemRequestQueue;// Instantiate the cacheCachecache=newDiskBasedCache(getCacheDir(),1024*1024);// 1MB cap// Set up the network to use HttpURLConnection as the HTTP client.Networknetwork=newBasicNetwork(newHurlStack());// Instantiate the RequestQueue with the cache and network.mRequestQueue=newRequestQueue(cache,network);// Start the queuemRequestQueue.start();Stringurl="http://www.myurl.com";// Formulate the request and handle the response.StringRequeststringRequest=newStringRequest(Request.Method.GET,url,newResponse.Listener<String>(){@OverridepublicvoidonResponse(Stringresponse){// Do something with the response}},newResponse.ErrorListener(){@OverridepublicvoidonErrorResponse(VolleyErrorerror){// Handle error}});// Add the request to the RequestQueue.mRequestQueue.add(stringRequest);...
如果你仅仅是想做一个单次的请求并且不想要线程池一直保留,你可以通过使用在前面一课:发送一个简单的请求(Sending a Simple Request)文章中提到Volley.newRequestQueue()方法在任何需要的时刻创建RequestQueue,然后在你的响应回调里面执行stop()方法来停止操作。但是更通常的做法是创建一个RequestQueue并设置为一个单例。下面将演示这种做法。
privatestaticMySingletonmInstance;privateRequestQueuemRequestQueue;privateImageLoadermImageLoader;privatestaticContextmCtx;privateMySingleton(Contextcontext){mCtx=context;mRequestQueue=getRequestQueue();mImageLoader=newImageLoader(mRequestQueue,newImageLoader.ImageCache(){privatefinalLruCache<String,Bitmap>cache=newLruCache<String,Bitmap>(20);@OverridepublicBitmapgetBitmap(Stringurl){returncache.get(url);}@OverridepublicvoidputBitmap(Stringurl,Bitmapbitmap){cache.put(url,bitmap);}});}publicstaticsynchronizedMySingletongetInstance(Contextcontext){if(mInstance==null){mInstance=newMySingleton(context);}returnmInstance;}publicRequestQueuegetRequestQueue(){if(mRequestQueue==null){// getApplicationContext() is key, it keeps you from leaking the// Activity or BroadcastReceiver if someone passes one in.mRequestQueue=Volley.newRequestQueue(mCtx.getApplicationContext());}returnmRequestQueue;}public<T>voidaddToRequestQueue(Request<T>req){getRequestQueue().add(req);}publicImageLoadergetImageLoader(){returnmImageLoader;}}
下面演示了利用单例类来执行RequestQueue的操作:
1234567
// Get a RequestQueueRequestQueuequeue=MySingleton.getInstance(this.getApplicationContext()).getRequestQueue();...// Add a request (in this example, called stringRequest) to your RequestQueue.MySingleton.getInstance(this).addToRequestQueue(stringRequest);