上一篇文章翻译了一下google的Volley官方文档,讲到了最基本的发送request。这一次我们来下一回:创建一个自定义RequestQueue。

这篇文章将会教你一步一步创建自己的RequestQueue,并定制你自己的行为。

第一步:使用定制的Network和cache

一个RequestQueue需要两样东西去完成他的工作:即发送请求的network和处理缓存的cache。在Volley中有两个实现的标准接口:那么DiskBasedCache提供一个

一个response对应一个文件的缓存和内存级别的索引。BasicNetwork提供基于Http client的网络传输。

BasicNetwork是Volley默认网络的网络接口,它必须被一个你正在使用的Http client初始化才能使用。就像下面这样:

 RequestQueue mRequestQueue;

 // Instantiate the cache
Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 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.example.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);

如果你只是一次性请求并且想要使用线程池,你可以在任意你想要的时候创建RequestQueue,然后再数据返回或者出错后调用stop()方法。但是更常用的方式是以单例的

方式去创建RequestQueue保证它运行在你的应用的生命周期内。

第二步:使用单例模式

如果你的应用持续使用网络,那么最好使用单例模式。实现它有很多种方式,推荐使用实现一个封装好RequestQueue和Volley其他功能的类。另一种方法是继承Application

并且在你的Application.onCreate()方法中创建RequestQueue ,但是这种方法是不被推荐的。一个单例可以实现同样的功能并且更加符合模块化的设计。

重要的一点是RequestQueue必须使用Application context而不是一个Activity Context。这可以保证RequestQueue在app的整个生命周期内都有效,而不是每次重新创建

Activity都要重新创建(比如手机从横屏到竖屏)。

下面是一个栗子:

 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>(20); @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;
}
}
 // 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使用指南第二回(来自developer.android)的更多相关文章

  1. Volley使用指南第三回(来自developer.android)

    继第二篇之后,再来Volley使用的教程的第三篇,有些翻译我是根据自己的理解,可能有错误的地方,还请多多包涵. 标准请求 这一回课将会告诉你Volley能够完成的3种请求类型 1.StringReqe ...

  2. Volley使用指南第一回(来自developer.android)

    最近闲来想看看android网络方面的东西.google在2013年发布了一个叫做Volley的网络请求框架,我看了一下官网,居然在training里面就有教程.首先,英文的东西看着 还是挺不爽的,特 ...

  3. Volley使用指南第四回(来自developer.android)

    Volley网络请求的第四篇,废话不多说,开始. 这一篇文章将会教你怎样在Volley支持的范围内定制一个请求. 第一步:写一个通用请求: 大多数请求都有已经写好的接口供你调用,如果你的请求是Stri ...

  4. 第三部分:Android 应用程序接口指南---第二节:UI---第十一章 样式和主题

    第11章 样式和主题 style是用于指定View或window的外观和格式的一系列属性的集合.style可以指定高(height).填补(padding).字体颜色.字体大小.背景颜色等等属性.st ...

  5. [翻译]现代java开发指南 第二部分

    现代java开发指南 第二部分 第二部分:部署.监控 & 管理,性能分析和基准测试 第一部分,第二部分 =================== 欢迎来到现代 Java 开发指南第二部分.在第一 ...

  6. 对怎样充分利用安卓官方开发网站的一个简单性介绍介绍-https://developer.android.google.cn/docs/

    一,谷歌的安卓官方网站-https://developer.android.google.cn/docs/ ,在网站里面可以查询开发文档,开发指导,设计原则,制作app的例子等等,无论对于新手还是老手 ...

  7. (备忘)Nginx中文手册(技术指南第二版)

    Nginx 常见应用技术指南[Nginx Tips] 第二版 目 录 一. Nginx 基础知识二. Nginx 安装及调试三. Nginx Rewrite四. Nginx Redirect五. Ng ...

  8. CSS Transform完全指南(第二版) #flight.Archives007

    Title/ CSS Transform完全指南(第二版) #flight.Archives007 序: 第7天了! 终身学习, 坚持创作, 为生活埋下微小的信仰. 我是忘我思考,共同进步! 简介: ...

  9. Knockout应用开发指南 第二章:监控属性(Observables)

    原文:Knockout应用开发指南 第二章:监控属性(Observables) 关于Knockout的3个重要概念(Observables,DependentObservables,Observabl ...

随机推荐

  1. UVALive 2238 Fixed Partition Memory Management(二分完美匹配)

    题意:计算机中有一些固定大小的内存,内存越大,处理速度越快.对于一个程序,加入不同的内存空间,处理所需时间不同.现给出m个内存空间,n个程序,对于每个程序程序,有k组数据(s,t),分别表示当程序 i ...

  2. apache开源项目 -- VXQuery

    Apache VXQuery 是一个兼容标准的 XML 查询处理器的实现.主要适合非常大量的 XML 数据处理. 参考: http://www.apache.org/

  3. Linux编译安装Darwin Streaming Server 6.0.3。。。

    目前主流的流媒体服务器有微软的windows media server.RealNetworks的Helixserver和苹果公司的Darwin Streaming Server. 微软的window ...

  4. 【转】IOS 计时器 NSTimer

    原文网址:http://blog.csdn.net/tangshoulin/article/details/7644124 1.初始化 + (NSTimer *)timerWithTimeInterv ...

  5. 安装--SambaServce

    参考地址:快跑蚂蚁的linux之旅--redhat安装配置samba实验win共享linux主机目录 1.使用rpm -qa|grep "samba",查看samba安装包是否安装 ...

  6. Linux User's Manual IOSTAT

    IOSTAT(1) Linux User's Manual IOSTAT(1) NAME iostat - Report Central Processing Unit (CPU) statistic ...

  7. POJ 1860 Currency Exchange

    题意:有n种货币,可以互相兑换,有m个兑换规则,兑换规则给出汇率r和手续费c,公式为b = (a - c) * r,从a货币兑换为b货币,问能不能通过不断的兑换赚钱,兑换期间手中的钱数不可以为负. 解 ...

  8. 六种排序的C++实现

    class SortNum { public: SortNum(); virtual ~SortNum(); void exchange(int& b,int& c);//交换数据 v ...

  9. Delphi的windows剪切板操作函数

    1. Clipbrd函数 function Clipboard: TClipboard;:若应用程序从未使用过剪贴板,则调用该函数形成新的剪贴板:若之前使用过剪贴板则返回使用过的剪贴板. 属性: As ...

  10. HDU 5749 Colmerauer 单调队列+暴力贡献

    BestCoder Round #84   1003 分析:(先奉上zimpha巨官方题解) 感悟:看到题解单调队列,秒懂如何处理每个点的范围,但是题解的一句算贡献让我纠结半天 已知一个点的up,do ...