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. java 邮箱验证公共方法

  2. c++ 接口继承和实现继承

    所谓接口继承,就是派生类只继承函数的接口,也就是声明:而实现继承,就是派生类同时继承函数的接口和实现. 我们都很清楚C++中有几个基本的概念,虚函数.纯虚函数.非虚函数. 虚函数: 虚函数是指一个类中 ...

  3. ios 环境配置网址

    http://blog.csdn.net/cwb1128/article/details/18019751

  4. jQuery1.9.1--queue队列源码分析(非动画部分)

    jQuery.extend({ // 显示或操作在匹配元素上执行的函数队列 queue: function (elem, type, data) { var queue; if (elem) { // ...

  5. Ogre1.8.1编译时大量warning的问题

    本文的编译环境为Windows7_SP1 + VS2010_SP1 :) 当编译Ogre1.8.1的源码时,会出现大量的warning,如图: 虽然没有太大影响,但是程序员都希望自己的程序是没有war ...

  6. Python中的两种列表

    python中有两种类型的列表:其中一种是用[]创建的列表,这种列表具有伸缩性,可以动态改变,而另外一种列表是用()创建,成为元组,元组一旦创建,在任何状况下都不能再改变,是一种常量列表. movie ...

  7. 如何用 Parse 和 Swift 搭建一个像 Instagram 那样的应用?(2)

    [编者按]本篇文章作者是 Reinder de Vries,既是一名企业家,也是优秀的程序员,发表多篇应用程序的博客.本篇文章中,作者主要介绍了如何基于 Parse 特点,打造一款类似 Instagr ...

  8. 国内Jquery CDN

    新浪CDN: <script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js">< ...

  9. UVA 11795

    B Mega Man’s Missions Input Standard Input Output Standard Output Mega Man is off to save the world ...

  10. (转)Android学习进阶路线导航线路(Android源码分享)

     转载请注明出处:http://blog.csdn.net/qinjuning 前言:公司最近来了很多应届实习生,看着他们充满信心但略带稚气的脸庞上,想到了去年的自己,那是的我是不是也和 现在的他们一 ...