配置一個 RequestQueue
先前的課程展示了利用 Volley 的默認行為優(yōu)勢如何使用便利方法 Volley.newRequestQueue 來配置一個 RequestQueue。這節(jié)課帶你顯式地創(chuàng)建一個 RequestQueue,為了配置自定義行為。
這節(jié)課也描述了推薦使用一個 singleton(單例) 來創(chuàng)建一個 App 生命周期級的的 RequestQueue
配置一個網(wǎng)絡和緩存
一個 RequestQueue 的工作需要做兩件事情:一個 network 來執(zhí)行 request 傳輸,一個 cache 來處理緩存。在 Volley toolbox 中有這些標準的實現(xiàn):DiskBasedCache 提供一個 one-file-per-response(一個響應對應一個文件)和一個 in-memory index,BasicNetwork 也提供了一個基于你偏好的 HTTP client 網(wǎng)絡傳輸實現(xiàn)
BasicNetwork 是 Volley 提供的默認網(wǎng)絡實現(xiàn),一個BasicNetwork 必須使用你 App 用來連接網(wǎng)絡的 HTTP client 來初始化。尤其是一個 HttpURLConnection
這個代碼片段展示了配置一個 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());
// 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);
// ...
如果只需要一次 request,并且不想常駐這個 thread pool,你可以在任何地方創(chuàng)建 RequestQueue 然后一旦請求 response 或者錯誤返回時調用 stop() 方法,使用在 Sending a Simple Request里描述的 Volley.newRequestQueue 那樣。但是更常見的使用情況是使用單例創(chuàng)建一個 RequestQueue 確保它能夠在整個 App 生命周期中可以運行,就像下面描述的那樣。
使用一個 Singleton Pattern (單例模式)
如果你的應用需要頻繁地使用網(wǎng)絡,設置一個 RequestQueue 單例對象可能是最有效的方法來使之在你的 App 整個生命周期中都有效。你可以采用不同的方式,這里推薦的方法是實現(xiàn)單例類來封裝 RequestQueue 和其他 Volley 方法。另一個方法是創(chuàng)建一個 Application 子類然后在 [Application.onCreate()] 方法中設置一個 RequestQueue,但是這種方法不推薦使用,一個靜態(tài)的單例類可以以更加模塊化的方法來提供相同的功能實現(xiàn)。
初始化 RequestQueue 的一個關鍵的概念是需要使用 Application 的 context,不是一個 Activity 的 context。這樣就會確保
RequestQueue 會被持續(xù)在 App 的整個生命周期中,而不是每次隨activity 的重創(chuàng)而重建(例如,當用戶旋轉手機屏幕時)
這里有一個提供 RequestQueue 和 ImageLoader 功能的單例類:
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;
}
}
這里有一些使用單例類來執(zhí)行 RequestQueue 操作的例子:
// 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);