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

Volley HTTP库系列教程(3)自定义RequestQueue和编写单例RequestQueue示例的更多相关文章

  1. Volley HTTP库系列教程(5)自定义一个Volley请求

    Implementing a Custom Request Previous  Next This lesson teaches you to Write a Custom Request parse ...

  2. Volley HTTP库系列教程(4)Volley内置的几种请求介绍及示例,StringRequest,ImageRequest,JsonObjectRequest

    Making a Standard Request Previous  Next   This lesson teaches you to Request a String 返回String Requ ...

  3. Volley HTTP库系列教程(2)Volley.newRequestQueue示例,发请求的流程,取消请求

    Sending a Simple Request Previous  Next This lesson teaches you to Add the INTERNET Permission Use n ...

  4. Volley HTTP库系列教程(1)简介及优点

    Transmitting Network Data Using Volley Get  started Dependencies and prerequisites Android 1.6 (API ...

  5. Spring 系列教程之自定义标签的解析

    Spring 系列教程之自定义标签的解析 在之前的章节中,我们提到了在 Spring 中存在默认标签与自定义标签两种,而在上一章节中我们分析了 Spring 中对默认标签的解析过程,相信大家一定已经有 ...

  6. React Native实战系列教程之自定义原生UI组件和VideoView视频播放器开发

    React Native实战系列教程之自定义原生UI组件和VideoView视频播放器开发   2016/09/23 |  React Native技术文章 |  Sky丶清|  4 条评论 |  1 ...

  7. Volley自定义Request及使用单例封装RequestQueue

    一.自定义Request Volley的所有的请求的超类型是Resuest,所有我们常用的请求都是这个类的子类,那么我们自定义View肯定也是基于这个类的. 案例: package com.zhy.v ...

  8. Spring Boot2 系列教程(六)自定义 Spring Boot 中的 starter

    我们使用 Spring Boot,基本上都是沉醉在它 Stater 的方便之中.Starter 为我们带来了众多的自动化配置,有了这些自动化配置,我们可以不费吹灰之力就能搭建一个生产级开发环境,有的小 ...

  9. Angular2入门系列教程2-项目初体验-编写自己的第一个组件

    上一篇 使用Angular-cli搭建Angular2开发环境 Angular2采用组件的编写模式,或者说,Angular2必须使用组件编写,没有组件,你甚至不能将Angular2项目启动起来 紧接着 ...

随机推荐

  1. vs2008 添加与修改模板.

    添加 我的模板: 路径:  C:\Users\Administrator\Documents\Visual Studio 2008\Templates\ItemTemplates\Visual C# ...

  2. UML交互图(转载)

    概述: 从名字交互作用很明显,图中是用来描述一些不同的模型中的不同元素之间的相互作用.所以,这种相互作用是动态行为的系统的一部分. 这种互动行为表示UML中的两个图,被称为序列图和协作图.这两个图的基 ...

  3. RT/Metro商店应用如何如何获取图片的宽高

    RT/Metro商店应用如何如何获取图片的宽高 var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms ...

  4. HDOJ1050

    Moving Tables Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Tot ...

  5. (链接保存)CentOS 6.6下yum快速升级内核

    (因Docker建议3.8以上kernel版本)这个方法升级很方便,保存链接备用: http://www.dadclab.com/archives/5340.jiecao Docker Engine安 ...

  6. Android 添加Button事件

    protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentV ...

  7. D3D Deferred Shading

    在3D图形计算中,deferred shading是一个基于屏幕空间的着色技术.之所以被称为deferred shading,是因为我们将场景的光照计算与渲染"deferred"到 ...

  8. Grid分组特性

    Ext.onReady(function () {                Ext.define('personInfo', {                    extend: 'Ext. ...

  9. Spark源码分析(二)-SparkContext创建

    原创文章,转载请注明: 转载自http://www.cnblogs.com/tovin/p/3872785.html  SparkContext是应用启动时创建的Spark上下文对象,是一个重要的入口 ...

  10. C语言运算符优先级表

    优先级 运算符 名称或含义 使用形式 结合方向 说明 1 [] 数组下标 数组名[常量表达式] 左到右   () 圆括号 (表达式)/函数名(形参表)   . 成员选择(对象) 对象.成员名   -& ...