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:

 HttpStack stack;
...
// 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.
}
Network network = new BasicNetwork(stack);

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

 RequestQueue mRequestQueue;

 // Instantiate the cache
Cache cache = new DiskBasedCache(getCacheDir(), * ); // 1MB cap // Set up the network to use HttpURLConnection as the HTTP client.
Network network = new BasicNetwork(new HurlStack()); // Instantiate the RequestQueue with the cache and network.
mRequestQueue = new RequestQueue(cache, network); // Start the queue
mRequestQueue.start(); String url ="http://www.myurl.com"; // Formulate the request and handle the response.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Do something with the response
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Handle error
}
}); // Add the request to the RequestQueue.
mRequestQueue.add(stringRequest);
...

  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:

 public class MySingleton {
private static MySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx; private MySingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue(); mImageLoader = new ImageLoader(mRequestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(); @Override
public Bitmap getBitmap(String url) {
return cache.get(url);
} @Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
} public static synchronized MySingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new MySingleton(context);
}
return mInstance;
} public RequestQueue getRequestQueue() {
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());
}
return mRequestQueue;
} public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
} public ImageLoader getImageLoader() {
return mImageLoader;
}
}

  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);

最新文章

  1. JS原生第二篇 (帅哥)
  2. ctags+cscope
  3. php浮点数计算问题
  4. XStream解析
  5. ado.net(class0503)
  6. Atom远程连接服务器报错服务器版本和客户端版本不一致
  7. 【CF】328 D. Super M
  8. 在KALI LINUX中安装JAVA JDK
  9. SQL Server 性能调优 之运行计划(Execution Plan)调优
  10. IIC-BUS INTERFACE
  11. php中常用的字符串查找函数strstr()、strpos()实例解释
  12. acm入门搜索-水池数目
  13. (NO.00004)iOS实现打砖块游戏(十三):伸缩自如,我是如意金箍棒(下)!
  14. jenkins忘记admin密码解决办法
  15. 排序大集合java
  16. C#面向对象之多态。
  17. as_matrix、保存训练模型
  18. 「NOI2018」你的名字
  19. 转:Hibernate query.list()之卡住问题
  20. wf-pagination-javascript 分页

热门文章

  1. poi过滤操作后产生新的sheet
  2. 【bzoj1009】[HNOI2008]GT考试
  3. extern关键字的使用
  4. JS中的间歇(周期)调用setInterval()与超时(延迟)调用setTimeout()相关总结
  5. css选择器浏览器支持情况
  6. ios 团购分类页面(9宫格)
  7. 加载gif动态图的三种方式
  8. POJ 2041
  9. C++堆栈与函数调用
  10. IDEA开发spark本地运行