Android网络通信必备神器Volley详解——自定义RequestQueue

来源:互联网 发布:手机之间蓝牙共享网络 编辑:程序博客网 时间:2024/06/16 10:01

上一篇文章讲解了如何使用Volley.newRequestQueue来新建一个默认的RequestQueue,本篇文章将要讲解的是新建一个RequestQueue的具体过程,从而可以新建一个自定义的RequestQueue。


设置网络和缓存


RequestQueue需要网络和缓存两部分才能工作。BasicNetwork提供基于HTTP的网络传输,DiskBaseCache提供具有内存索引的one-file-per-response缓存

设置自定义的RequestQueue

RequestQueue mRequestQueue;// Instantiate the cacheCache 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());<strong>// Instantiate the RequestQueue with the cache and network.mRequestQueue = new RequestQueue(cache, network);</strong>// Start the queuemRequestQueue.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);

从上面的示例可以看到,Cache的大小可以自己设置的,这里我们设置了1M的缓存。Network使用的是基本的HttpURLConnection。

使用单例模式

你可以在你需要的时候创建一个RequestQueue,并在不需要的时候调用stop()销毁他,但是更普遍的是把RequestQueue设计成单例模式。实现单例模式的方法有很多种,我推荐使用一个类来封装RequestQueue和Volley的功能。RequestQueue必须使用Application.contex来初始化,不能使用Activity.contex。这样可以确保RequestQueue在整个app的声明周期中都可以使用。
下面是一个单例模式的例子
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 RequestQueueRequestQueue queue = MySingleton.getInstance(this.getApplicationContext()).    getRequestQueue();// ...// Add a request (in this example, called stringRequest) to your RequestQueue.MySingleton.getInstance(this).addToRequestQueue(stringRequest);



1 0
原创粉丝点击