Android網絡通信必備神器Volley詳解——自定義RequestQueue

上一篇文章講解了如何使用Volley.newRequestQueue來新建一個默認的RequestQueue,本篇文章將要講解的是新建一個RequestQueue的具體過程,從而可以新建一個自定義的RequestQueue。


設置網絡和緩存


RequestQueue需要網絡和緩存兩部分才能工作。BasicNetwork提供基於HTTP的網絡傳輸,DiskBaseCache提供具有內存索引的one-file-per-response緩存

設置自定義的RequestQueue

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

<strong>// Instantiate the RequestQueue with the cache and network.
mRequestQueue = new RequestQueue(cache, network);</strong>

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

從上面的示例可以看到,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 RequestQueue
RequestQueue queue = MySingleton.getInstance(this.getApplicationContext()).
    getRequestQueue();

// ...

// Add a request (in this example, called stringRequest) to your RequestQueue.
MySingleton.getInstance(this).addToRequestQueue(stringRequest);



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章