Volley HTTP库系列教程(3)自定义RequestQueue和编写单例RequestQueue示例
1.This lesson teaches you to
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: DiskBasedCache
provides 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
:
- Use
AndroidHttpClient
for apps targeting Android API levels lower than API Level 9 (Gingerbread). Prior to Gingerbread,HttpURLConnection
was unreliable. For more discussion of this topic, see Android's HTTP Clients. - Use
HttpURLConnection
for apps targeting Android API Level 9 (Gingerbread) and higher.
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示例的更多相关文章
- Volley HTTP库系列教程(5)自定义一个Volley请求
Implementing a Custom Request Previous Next This lesson teaches you to Write a Custom Request parse ...
- Volley HTTP库系列教程(4)Volley内置的几种请求介绍及示例,StringRequest,ImageRequest,JsonObjectRequest
Making a Standard Request Previous Next This lesson teaches you to Request a String 返回String Requ ...
- Volley HTTP库系列教程(2)Volley.newRequestQueue示例,发请求的流程,取消请求
Sending a Simple Request Previous Next This lesson teaches you to Add the INTERNET Permission Use n ...
- Volley HTTP库系列教程(1)简介及优点
Transmitting Network Data Using Volley Get started Dependencies and prerequisites Android 1.6 (API ...
- Spring 系列教程之自定义标签的解析
Spring 系列教程之自定义标签的解析 在之前的章节中,我们提到了在 Spring 中存在默认标签与自定义标签两种,而在上一章节中我们分析了 Spring 中对默认标签的解析过程,相信大家一定已经有 ...
- React Native实战系列教程之自定义原生UI组件和VideoView视频播放器开发
React Native实战系列教程之自定义原生UI组件和VideoView视频播放器开发 2016/09/23 | React Native技术文章 | Sky丶清| 4 条评论 | 1 ...
- Volley自定义Request及使用单例封装RequestQueue
一.自定义Request Volley的所有的请求的超类型是Resuest,所有我们常用的请求都是这个类的子类,那么我们自定义View肯定也是基于这个类的. 案例: package com.zhy.v ...
- Spring Boot2 系列教程(六)自定义 Spring Boot 中的 starter
我们使用 Spring Boot,基本上都是沉醉在它 Stater 的方便之中.Starter 为我们带来了众多的自动化配置,有了这些自动化配置,我们可以不费吹灰之力就能搭建一个生产级开发环境,有的小 ...
- Angular2入门系列教程2-项目初体验-编写自己的第一个组件
上一篇 使用Angular-cli搭建Angular2开发环境 Angular2采用组件的编写模式,或者说,Angular2必须使用组件编写,没有组件,你甚至不能将Angular2项目启动起来 紧接着 ...
随机推荐
- BZOJ2752: [HAOI2012]高速公路(road)
2752: [HAOI2012]高速公路(road) Time Limit: 20 Sec Memory Limit: 128 MBSubmit: 608 Solved: 199[Submit][ ...
- c++ 继承和组合的区别
.什么是继承 A继承B,说明A是B的一种,并且B的所有行为对A都有意义 eg:A=WOMAN B=HUMAN A=鸵鸟 B=鸟 (不行),因为鸟会飞,但是鸵鸟不会. .什么是组合 若在逻辑上A是B的“ ...
- boost 相关
编译boost: 1.打开Microsoft Visual Studio 2010 -> Visual Studio Tools -> Visual Studio Command Prom ...
- 在线编辑器 (UBB, FCK)
这里主要说明一下:UBB UBB 使用类型HTML的语法. UBB相对FCK的HTML方式, 安全性高. 用户不可以直接嵌入HTML代码. UBB 在线编辑器(JS版): http://www. ...
- C51关键字
C51 中的关键字 关键字 用途 说明 auto 存储种类说明 用以说明局部变量,缺省值为此 break 程序语句 退出最内层循环 case 程序语句 Switch语句中的选择项 char 数据类型说 ...
- 使用CSS3实现超炫的Loading(加载)动画效果
SpinKit 是一套网页动画效果,包含8种基于 CSS3 实现的很炫的加载动画.借助 CSS3 Animation 的强大功能来创建平滑,易于定制的动画.SpinKit 的目标不是提供一个每个浏览器 ...
- NGUI 实现 透明底图遮罩 && 人物像素变黑
今天 UI 那边要求实现一个 透明底图遮罩 与 变黑 的效果. 刚开始考虑使用 shader 实现一个 网上搜了一下,发现了这个,但是底图需要不透明才行,不然他会把 底图的不遮罩部分的透明部分 进行颜 ...
- Android中如何查看内存(上)
文章参照自:http://stackoverflow.com/questions/2298208/how-to-discover-memory-usage-of-my-application-in-a ...
- Codeforces Round #263 (Div. 2) D. Appleman and Tree(树形DP)
题目链接 D. Appleman and Tree time limit per test :2 seconds memory limit per test: 256 megabytes input ...
- spring_150805_datasource
实体类: package com.spring.model; public class DogPet { private int id; private String name; private in ...